I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
Here's my code...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0, do max = num just like you already do with min.
It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.
Related
this was supposed to be fairly simple, but apparently somethings wrong with my control boolean, when I input a negative number instead of ending the loop it throws an exception, any help is appreciated.
import java.util.*;
public class AverageMinMax {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double average;
int count = 0, sum = 0, next;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
boolean areMore = true;
System.out.println("Please enter the numbers you wish to evaluate:");
System.out.println("Followed by a negative number");
// not sure why i used a do while loop but it works i guess
do {
next = keyboard.nextInt();
sum = sum + next;
next++;
if (next < 0)
areMore = false;
} while (areMore == true);
{
sum = sum + next;
average = sum / count;
{// the minmum and max values
if (next > max)
max = next;
if (next < min)
min = next;
}
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
}
Error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.test.task.AverageMinMax.main(AverageMinMax.java:29)
Your issues:
You increase next instead of count.
Outsider (sum = sum + next) is also wrong. You should not add next after loop breaks.
Min-max should be calculated inside the loop.
Some improvement suggestions:
Use while it is cleaner than do-while.
Use hasNextInt to check if it is a number or not.
If your input is a char or any special character while loop breaks.
import java.util.*;
public class AverageMinMax {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double sum = 0, average =0;
int count = 0, next = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
System.out.println("Please enter the numbers you wish to evaluate:");
System.out.println("Followed by a char or any special character to calculate and exit");
// use while it is more cleaner.
// use hasNextInt to check if it is number or not
// if your input is a char or any special character while loop breaks
while (keyboard.hasNextInt()) {
next = keyboard.nextInt();
sum = sum + next;
// the minmum and max values
if (next > max)
max = next;
if (next < min)
min = next;
count++;
}
average = sum / count;
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
}
}
Issues
count is not incremented and its causes divide by 0 error
computation of max, min, sum, average seems incorrect
solution
Repeated read input(integer) from user
if the input is positive, add to sum, update min, update max and update count
if its negative, break the input loop
if any input is passed, then compute average
if no input is passed, then do not compute average
import java.util.Scanner;
class AverageMinMax {
public static void main(String[] args) {
final Scanner keyboard = new Scanner(System.in);
int count = 0, sum = 0, min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
System.out.println("Please enter the numbers you wish to evaluate.");
System.out.println("Followed by a negative number to stop input");
do {
final int next = keyboard.nextInt();
if (next < 0) {
break;
}
sum = sum + next;
max = Math.max(max, next);
min = Math.min(min, next);
count++;
} while (true);
if (count > 0) {
double average = (sum * 1.0) / count; // need to multiply by 1.0 to have fraction
System.out.println("Your average is: " + average);
System.out.println("Your maximum number is: " + max);
System.out.println("Your minimum number is: " + min);
} else {
System.out.print("No input to process");
}
}
}
You are getting ArithmeticException because you initialize count to 0. But after that when you are getting input from console. instead of increasing the count and doing count++. You are doing next++ in the loop.
And also getting the min max should also needs to be done in loop currently they are just in block. Although they are not responsible for your error of divide by zero.
this line is
average = sum / count;
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have the following error
cannot find symbol: variable num
in all the if statements.
This is my current code.
Scanner console = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
do{System.out.println("Type a number (or -1 to stop): ");
int num = console.nextInt();
}while(!num == -1);{
System.out.print(+ num );
}if (min < num) {
num = min;
}if (num > max) {
max = num;
}
System.out.println("maximum was : " + max);
System.out.println("minimum was : " + min);
}
Help.
The issue lies with the scope of the variable num. You have declared it inside the do block so num will not be accessible outside the do block. Also, your if condition is not correct.
Implement this and the code should run just fine:
Scanner console = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int num = 0;
do{
System.out.println("Type a number (or -1 to stop): ");
num = console.nextInt();
} while(num != -1);
if (min < num) {
num = min;
} if (num > max) {
max = num;
}
System.out.println("maximum was : " + max);
System.out.println("minimum was : " + min);
You want to test for max and min inside the loop and not after it terminates, since that means that you are only testing the last number that was entered – which will always be -1 (minus one). You also write that you want to ignore the -1. I believe the following code does what you require – which is to find the minimum and maximum of a series of numbers that are entered by the user.
Scanner console = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
int num = 0;
do {
System.out.print("Type a number (or -1 to stop): ");
num = console.nextInt();
console.nextLine();
if (num != -1) {
if (num > max) {
max = num;
}
if (num < min) {
min = num;
}
}
} while (num != -1);
if (max == Integer.MIN_VALUE) {
System.out.println("No numbers were entered.");
}
else {
System.out.printf("max = %d , min = %d%n", max, min);
}
Note that you need to consume the <ENTER> key that the user presses after entering each number. Hence the call to method nextLine() of class Scanner. Refer to Scanner is skipping nextLine() after using next() or nextFoo()?
If the first number entered is -1 then the user did not enter any numbers and therefore there will be no maximum or minimum. If the first number entered is -1, then the value of max will be Integer.MIN_VALUE.
Syntax problem
while (!num == -1);{
Won't work, because Java does not allow an negate operator (!) to be at the start of a non-type boolean. You cannot do a local-body at the while loop within a do-while loop.
The fix here
You can fix your code by simply changing this line to:
while (num != -1); {...}
Therefore you have to remove the whole while body and replace it with
while (num != -1);
So removing the bracket
I highly recommend you to learn the Java syntax.
Sincerly, Vinzent
So my code works in all test cases except for when there are only two integers.
Example if user inputs: terminating number as -1 and then inputs 1,2 and then -1 again the smallest numbers are 1,1 and not 1,2
Terminating number is just the way to end the sequence/program.
public static void main(String[] args) {
double num;
double min = 0;
double min2 = 0;
System.out.println("Enter terminating value:");
int term = IO.readInt();
System.out.println("Enter next value:");
num = IO.readDouble();
if(num == term){
IO.reportBadInput();
main(args);
}
int count = 0;
min = num;
min2 = num;
do{
num = IO.readDouble();
if(num!= term && num < min) {
min2 = min;
min = num;
}
else if (num!= term && num < min2) {
min2 = num;
}
count++;
}while (num != term);
if(count < 2){
IO.reportBadInput();
main(args);
}
else{
IO.outputDoubleAnswer(min);
IO.outputDoubleAnswer(min2);
}
}
The issue with your code lies in setting both minimal values to the number that was first entered. This is bad because if the user enters the smallest value first, both min and min2 already contain the minimum value. That means the condition input < min2 is always false, causing min2 to always contain the value the user has entered first.
To fix this, simply set the value of min2 to a value which is larger than any other value the user could enter (for example Double.MAX_VALUE or Double.POSITIVE_INFINITY).
Just as a hint concerning the error-handling part of your code: if you call main again after reminding the user that their input was invalid, make sure to add a return behind that call or the execution will continue after the called main method is finished. Something like this:
if (count < 2) {
IO.reportBadInput();
main(args);
return;
}
I am writing a program that reads a sequence of positive integers input by the user. User will only enter one integer at a time.Then it will compute the average of those integers. The program will end when user enters 0. (0 is not counted in the average).The program will print out the average once the program ends.
Question: My code stops working when I gets to the while loop hence it doesn't compute the input by user, hence prints out nothing. Why doesn't my while loop compute the average from the user's inputs? Appreciate your guidance :)
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum;
sum = 0;
double average;
Scanner input = new Scanner(System.in);
int count; count = 0;
average = 0;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
System.out.println("Average = " + average);
}
}
This is because you are never actually summing over more than one integer. The user only ever enters one number. As a result your loop is essentially acting on just the one number. You need to put the input inside the while loop and save a running sum and count there. Something more like this
while (integer != 0) {
count += 1;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
Explanation
First of all, when you define data types, you can set their default value in the definition. Ex:
double sum = 0;
vs
double sum;
sum = 0;
Secondly, sum = sum + integer; is the same as: sum += integer;
Thirdly, count = count + 1; is the same as: count += 1 OR (and better yet), count++;
As for your actual algorithm, there is one problem and one suggestion:
you are not changing integer's value after each loop. So, you can
either do that in the while condition: while ((integer =
input.nextInt()) != 0) { or, at the end of each loop:
while (integer != 0) {
count ++;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
This is a suggestion for technically better code (in my opinion), but it looks better, is more intuitive and requires less calculations to calculate the average after the while loop is done instead of during. That way, you only calculate it once, where needed, vs. every loop, which is not needed.
________________________________________________________________________________
The Code (complete class)
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Please enter an integer: ");
// set integer = to the nextInt() while looping so it calculates properly
while ((integer = input.nextInt()) != 0) {
count ++;
sum += integer;
}
average = sum / count; // calculate the average after the while-loop
System.out.println("Average = " + average);
}
}
________________________________________________________________________________
Example input/output:
Please enter an integer:
5
10
15
0
Average = 10.0
So it did 5 + 10 + 15 = 30 (which is the sum), and then the average is 30 / 3 (30 is the sum, 3 is the count), and that gave you Average = 10.0.
You need to move integer = input.nextInt(); inside the loop, so your program will collect inputs in a loop. See the corrected version:
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer = 0, count = 0;
double sum = 0.0, average = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
System.out.println("Average = " + average);
}
}
The problem is that the input.nextInt() should be part of the loop. The way you wrote it, the code gooes into an infinite loop whenever the first input is non-zero. Instead, do:
while ((integer = input.nextInt()) != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
In the loop:
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
This will only stops when integer is 0, but this variable is not changing in the loop, so it will never be 0 if it wasn't already in the first place.
According to what you said you want to do, you should probably repeat the call to integer = input.nextInt(); inside your loop, lke this:
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
Also, as others have said, you only need to compute the average once after the loop, so I moved it too.
As the title stated, I am trying to find the maximum and minimum values, the amount of evens and odds numbers, and the average of all inputted numbers.
The problem. As I run my code, my odds and evens counter seem to read their opposite, odd would read an even input and even would read an odd input. As for my average, I have no clue what is wrong with it, all I know is that it would only find the average of a proper fraction.
Also, as I input quit, I get for my largest number 214XXXXXXXX
Example of my output will be pasted at the end.
System.out.println("Enter a sequence of integers. Any non-integer to quit");
Scanner scan = new Scanner(System.in);
int min = Integer.MAX_VALUE;
int max = 0;
int count = 0;
int sum = 0;
int oddsCounter = 0;
int evensCounter = 0;
int getInt;
double average = 0;
while (scan.hasNextInt()) {
getInt = scan.nextInt();
if (getInt % 2 == 0) {
evensCounter++;
System.out.println("even: " + evensCounter);
} else {
oddsCounter++;
System.out.println("odd: " + oddsCounter);
}
if (getInt < min) {
min = getInt;
} else if (getInt > max) {
max = getInt;
}
sum += getInt;
System.out.println("sum " + sum);
count++;
System.out.println("count " + count);
average = (double) sum / (count);
System.out.println("average " + average);
}
System.out.println("smallest: " + min);
System.out.println("largest: " + max);
System.out.println("even: " + oddsCounter);
System.out.println("odd: " + evensCounter);
System.out.println("average: " + average);
Result:
Enter a sequence of integers. Any non-integer to quit
9 //input 1
odd: 1
sum 9
count 1
average 9.0
3 //input 2
odd: 2
sum 12
count 2
average 6.0
7 //input 3
odd: 3
sum 19
count 3
average 6.333333333333333
1 //input 4
odd: 4
sum 20
count 4
average 5.0
q //input 5: QUIT
smallest: 1
largest: 7 //This should be 9
even: 0
odd: 4
average: 5.0
Result 2:
Enter a sequence of integers. Any non-integer to quit
q //quit
smallest: 2147483647 //This should be 0
largest: 0
even: 0
odd: 0
average: 0.0
Any help would be appreciated. Thank you!
Take out else before checking if getInt is greater than max. You need to check for both the conditions, so don't put else there.
if (getInt < min) {
min = getInt;
} else if (getInt > max) {
max = getInt;
}
Change above code as mentioned below . You have to check both condition so change else if to if.
In if - else if
once a condition is satisfied, the appropriate statements are executed
and the remaining conditions are not evaluated.
if (getInt < min) {
min = getInt;
}
if (getInt > max) {
max = getInt;
}
First
9 wasn't assigned to max. Since 9 < min, The code evaluates min = getInt; and skip the else if part.
It should be :
if (getInt < min)
{
min = getInt;
}
if (getInt > max)
{
max = getInt;
}
Because a number can be both min and max.
Second
smallest: 2147483647 //This should be 0
This happen because you type in a character but scan in as an integer by usinggetInt = scan.nextInt(); (as well as store the input as an int).
You can fix this scan in the input as String first. Then, you determine if the input is an int or not by creating a method to check it. :
public static boolean isInteger(String s)
{
try
{
Integer.parseInt(s);
}
catch(NumberFormatException e)
{
return false;
}
// only got here if we didn't return false
return true;
}
Then, check if the input is an integer before you do the calculation.
As to your other problem, you have to initialize min as 0.
After that, check if the input is your first, and if so set min as that.
boolean isFirst = true;
while (scan.hasNextInt()) {
getInt = scan.nextInt();
if(isFirst)
{
min = getInt;
isFirst=false;
}
//Rest of your code
}