so I'm trying to find the min, max, and average number of the numbers input. Everything works fine, although I do not want input less than 0 or greater than 100. When I input a number less than 0 or greater than 100 it still records it as the min/max. I do not want this! How would I not take input that is less than 0 or greater than 100?
Thanks!
import java.text.DecimalFormat;
import java.util.Scanner;
public class ExamGrades {
public static void main(String[]args){
Scanner scan = new Scanner(System.in );
int number = 0;
double total = 0;
int minimum;
int maximum = 0;
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
minimum=number;
total += number;
for(int i = 2; i<11; i++){
if(number<0 || number >100){
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
i--;
}
else{
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
total += number;
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + minimum);
System.out.println("The maximum is: " + maximum);
System.out.println("The average is: " + oneDecimalPlace.format((total) / 10.0 ));
}
}
Let's say you entered 5 for integer one, then 102 for the second integer. What's going to happen? Well before you entered 102, number was 5, so it will go into the else block.
It'll say:
Please enter integer 2:
then you type: 102
So then what? Well the next piece of code is:
number = scan.nextInt(); and then it goes through the if-statements right below it to determine if it's a maximum. Nothing is stopping it.
Try this code instead of your loop:
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
// keep them in a loop until they enter a valid number
while (number < 0 || number > 100) {
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
}
// after they entered a valid number, add it to the series
minimum = number;
total += number;
for(int i = 2; i < 11; i++) {
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
// keep them in a loop until they enter a valid number
while (number < 0 || number > 100) {
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
}
// after they entered a valid number, add it to the series
total += number;
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
problem:
if(number<0 || number >100)
It will return false when number is 100 or 0 thus accepting it and executing you else block.
Is 100>100 answer false because they are equal, not greater than the other
solution:
if(number<1 || number >99)
EDit:
public static void main(String[]args){
Scanner scan = new Scanner(System.in );
int number = 0;
double total = 0;
int minimum = 0;
int maximum = 0;
System.out.println("Please enter the first integer: ");
number = scan.nextInt();
if(number>1 && number <99)
{
minimum=number;
total += number;
}
for(int i = 2; i<11; i++){
if(number<1 || number >99){
System.out.println("Please enter a valid number: ");
number = scan.nextInt();
i--;
}
else{
System.out.println("Please enter integer " + i + ":");
number = scan.nextInt();
total += number;
if(number>1 && number <99)
{
if(number<minimum)
minimum = number;
if(number>maximum)
maximum = number;
}
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + minimum);
System.out.println("The maximum is: " + maximum);
System.out.println("The average is: " + oneDecimalPlace.format((total) / 10.0 ));
}
Here is an Example.Exceptions are not handled so put a Try-catch to String to Integer Conversion If you want.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Numbers{
public static void main(String x[]){
Scanner scn=new Scanner(System.in);
int Total=0,Max=0,Min=Integer.MAX_VALUE;
for(int i=0;i<10;){
System.out.print("Enter Number :");
int NumberOne=Integer.parseInt(scn.nextLine());//Put a Try catch If needed
if(NumberOne>0&&NumberOne<100){
Total+=NumberOne;
Max=(Max>NumberOne)?Max:NumberOne;
Min=(Min<NumberOne)?Min:NumberOne;
i++;
}else{
System.out.print("Number Invalid");
}
}
DecimalFormat oneDecimalPlace = new DecimalFormat("##.#");
System.out.println("The minimum is: " + Min);
System.out.println("The maximum is: " + Max);
System.out.println("The average is: " + oneDecimalPlace.format((Total) / 10.0 ));
}
}
Related
So to clarify, when the program asks the user for number 1: if the user were to input a letter, I need the program to tell the user that there was an input mismatch, then ask the user for number 1 again. This needs to be achieved using only one single for loop, and there can be no negative numbers that affect the sum or the average. Here's what I have so far:
import java.util.*;
import java.text.*;
class fivePositiveNumbers{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
for(int i = 1; i <= 5; i++){
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
sum = sum + userNumber;
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
}
Use a while or a for loop that will increment the loop count ONLY IF a valid input is provided. Your solution increments the loop counter automatically regardless of the validity of the input.
int i = 1;
while (i <= 5) {
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
sum = sum + userNumber; // this belongs after the negative check
i++; // increment the count after all validations are successfully completed
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
}
If you choose to use a for loop, remove the counter increment out of the loop declaration
for (int i = 1; i <= 5;) {
// your logic and exception handling here
i++; // as in the while, increment only after all validations are successfully completed
}
Another point... I don't think it is necessary to throw an exception if the number is negative. I think it is better to simply execute a continue to avoid incrementing the loop counter. This is the result of this:
This program will give the sum and average of 5 positive integers,
Enter number 1:
-5
The integer must be positive.
Enter number 1:
-2
The integer must be positive.
Enter number 1:
-3
The integer must be positive.
Enter number 1:
-4
The integer must be positive.
Enter number 1:
-5
The integer must be positive.
Enter number 1:
1
Enter number 2:
2
Enter number 3:
3
Enter number 4:
5
Enter number 5:
4
The sum is 15 and the average of your 5 numbers is 3.
As you can see, I entered several negative numbers and the program continued to run without incrementing the loop counter. The complete solution with continue:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
for(int i = 1; i <= 5; ){
System.out.println("Enter number " + i + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
System.err.println("The integer must be positive.");
continue;
}
sum = sum + userNumber;
i++;
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
class fivePositiveNumbers{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int userNumber;
int sum = 0;
System.out.println("This program will give the sum and average of 5 positive integers,");
int ctr = 0;
for(;;){
System.out.println("Enter number " + (ctr+1) + ": ");
try{
userNumber = keyboard.nextInt();
if(userNumber <= 0){
throw new Exception("The integer must be positive.");
}
sum = sum + userNumber;
ctr++;
} catch(InputMismatchException e){
System.out.println("This data type is incorrect.");
keyboard.nextLine();
} catch(Exception e){
System.out.println(e.getMessage());
keyboard.nextLine();
}
if (ctr == 5) break;
}
System.out.println("The sum is " + sum + " and the average of your 5 numbers is " + sum / 5 + ".");
}
}
The idea of my code is that it asks user the income of each month, until the user imputs negative value, which should not be added to the total income and which should be shown in output, but ignored in calculations.
Then the code calculates the total income (ignoring the last negative value), the average income (ignoring the negative value) and the biggest/maximum value of all values. I don't have problems getting right that maximum value. But how could I ignore the negative income in calculations, and maby even not to add it at all to the array?
The problem is that the calculation adds also the negative value/income to the total sum and average income calculations. And it does not ignore the month of the negative income.
Here is my code so far:
package income;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Income {
public static void main(String[] args) {
int sum = 0;
int months = 0;
Scanner input = new Scanner(System.in);
System.out.println("Write the income of each month.");
ArrayList<Integer> array = new ArrayList<Integer>();
System.out.println("Write the income of month 1: ");
int income = input.nextInt();
sum += income;
months++;
array.add(income);
while(true){
months++;
System.out.println("Write " + months + ". month income: ");
if(income >= 0){
income = input.nextInt();
sum += income;
array.add(income);
}
else if (income < 0){
break;
}
}
/*This did not work
for(int i= 0; i < array.size(); i++){
if(income < 0){
array.remove(i);
}
}*/
months--;
System.out.println("The total income is " + sum);
System.out.println("The average income is " + sum/months);
//This one below works fine
System.out.println("The biggest income is " + Collections.max(array));
}
}
Although you are indeed adding the last negative number into account in the calculations, this is not the ultimate reason why your code is not working. You are actually checking whether the previous input you read is greater than 0 here:
while(true){
months++;
System.out.println("Write " + months + ". month income: ");
if(income >= 0){ <------
income = input.nextInt();
So the loop will only stop if the previous input is less than 0. In other words, when you enter e.g. -1 in, the input is not checked until the next iteration of the loop, at which point -1 has already been added to the array. Therefore, you should instead check income >= 0 immediately after nextInt:
System.out.println("Write the income of each month.");
ArrayList<Integer> array = new ArrayList<>();
while(true){
months++;
System.out.println("Write the income for month" + months + ":");
int income = input.nextInt();
if(income >= 0){
sum += income;
array.add(income);
}
else {
break;
}
}
Note that I've also removed the bit between Write the income of each month. and the while loop, as it is redundant.
I suppose this is what you are looking for.
var list = new ArrayList<Integer>();
var in = new Scanner(System.in);
var i = 0;
System.out.println("Write Income of Each Month.");
while (true)
{
System.out.print("Write " + ++i + ".month income : " );
int num = in.nextInt();
if (num < 0)
{
int sum = list.stream().mapToInt(Integer::intValue).sum();
double avg = (double) sum / --i;
int max = Collections.max(list);
System.out.printf("Sum : %d\nAverage : %f\nBiggest Number : %d\nNegative No. %d", sum ,avg, max, num);
break;
}
else
{
list.add(num);
}
}
You could use the Integer.signum(int) function to know whether the value is negative (returned value = -1) or zero (returned value = 0) or positive (returned value = 1). So, basically ignore if Integer.signum(income) == -1
I was creating a program in which the user is repeatedly asked to enter input until the Scanner reads 0. For some odd reason whenever I enter an integer, it appears before the next message appears asking for input.Any help to resolve this is much appreciated.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer, the input ends if it is 0: ");
int number;
int posCount = 0;
int negCount = 0;
int total = 0;
while((number = input.nextInt()) != 0) {
System.out.println("Enter an integer, the input ends if it is 0:");
if(number < 0) {
negCount++;
}
if(number > 0) {
posCount++;
}
total += number;
}
System.out.println("The number of negatives is " + negCount);
System.out.println("The number of positives is " + posCount);
System.out.println("The total is " + total);
Do use System.out.print() isntead of System.out.println().
System.out.print("Enter an integer, the input ends if it is 0: ");
My code is supposed to ask for a name, ask for a number between one and ten, print the numbers from 1 to the number the user entered except every third number should
be the user's name that was entered at the beginning of the program, print the even numbers, continually ask the user for numbers until the user enters the sentinel, and then print the total of the numbers entered. (I know, that's a lot.) My code is running fine, the only problem I am having is with the last part. Even when the user enters the sentinel, which in this case is -1, the program still asks for another entry.
Did I do something wrong when declaring the variable or can someone explain how to fix my problem? Here is my code.
import java.util.Scanner;
/**
*
* #author Home
*/
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner( System.in);
System.out.print( "Enter your name: ");
String name = scan.nextLine();
System.out.print( "Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print( "No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for(int i =2; i<=number; i+=2)
System.out.print(i + " ");
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
System.out.println(" Enter a number or -1 to finish. " );
inputNumber = scan.nextInt();
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
number = scan.nextInt();
}
System.out.println( "The total is " + total);
}
}
Solution:
You get input from user and saving that input in varible called number but you are checking your while against inputNumber.
while ( inputNumber != SENTINEL )
{
total += number;
System.out.print("Enter the next number or '-1' to finish. ");
inputNumber = scan.nextInt(); <<< not number should be inputNumber
}
public class NewClass1 {
public static void main(String[] args) {
int number;
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.print("Please enter a number between 1 and 10: ");
number = scan.nextInt();
//asks for a number between one and ten until I get number within that range,
while (number < 1 || number > 10) {
System.out.print("No, between 1 and 10: ");
number = scan.nextInt();
}
for (int i = 1; i <= number; i++) {
if (i % 3 == 0) {
System.out.print(name + " ");
} else {
System.out.print(i + " ");
}
}
System.out.println();
for (int i = 2; i <= number; i += 2) {
System.out.print(i + " ");
}
System.out.print("are the even numbers.");
final int SENTINEL = -1;
int inputNumber;
int total = 0;
do {
System.out.println(" Enter a number or -1 to finish. ");
inputNumber = scan.nextInt();
if(inputNumber!= SENTINEL){
total+=inputNumber;
}
} while (inputNumber != SENTINEL);
System.out.println("The total is " + total);
}
}
Hi all thanks for taking the time, I am continuosly getting an infinate loop when i am inserting the variable m could anyone please take a look thanks.
public static void main program7_2(String args [])
{
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while((n%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while((m%2)== 0)
{
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum =0;
for (int i = n; n<=m; i++)
{
if ((i%2) != 0)
sum = sum + i;
}
System.out.println("Sum of the numbers between "+n+ " and " +m+": " + sum);
}
The problem of the program is to enter 2 odd numbers and get the sum of the odd numbers in between
Thanks and regards
Instead of n<=m in your for loop use i<=m since you are using i as your counter and not n
This is the error :
for (int i = n; n<=m; i++) /* terminating condition "n<=m" is never met here */
{
if ((i%2) != 0)
sum = sum + i;
}
Why : this loop increments i but terminating condition is n<=m which is never met....so either do i<n Or i<m which ever suits you for terminating the condition!!
if u want to get the sum of nubers between those two use
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number: ");
int n = sc.nextInt();
while ((n % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
n = sc.nextInt();
}
System.out.println("Please enter the second number: ");
int m = sc.nextInt();
while ((m % 2) == 0) {
System.out.println("The number you entered is incorrect please enter an odd number:");
m = sc.nextInt();
}
int sum= 0;
for (int i = n; i <= m; i++) {
sum = sum + i;
}
System.out.println("Sum of the numbers between " + n + " and " + m + ": " + sum);
}
}