If you could give me some help with an assignment I have for my Java class, I'd greatly appreciate it. The prompt for the question is:
Write a program to read a list of non-negative integers and to display the largest integer, the smallest integer, and the average of all the integers. The user indicates the end of the input by entering a negative sentinel value that is not used in finding the largest, smallest, and average values. The average should be a value of type double so that it is computed with a fractional part.
The problem I'm experiencing with my code is that when run, the loop does not finish unless the first value entered is negative, in which case it returns:
The maximum number entered was: 0 The minimum number entered was: 0 The average of the numbers entered was: NaN
Please help! Thanks. -Sam
code:
package blah;
import java.util.Scanner;
public class blahblah
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println ("Please enter a list of positive integers.");
System.out.println ("Please enter a negative integer when finished.");
int in = 0;
int max = 0;
int min = 0;
int sum = 0;
int count = 0;
in = keyboard.nextInt();
while (in>=0)
{
if (in > max) {
in = max;
}
if (in < min) {
in = min;
}
sum += in;
count++;
if (in < 0) {
break;
}
}
System.out.println("The maximum number entered was: " + max);
System.out.println("The minimum number entered was: " + min);
System.out.println("The average of the numbers entered was: " + (double)sum/count);
}
}
in=max;tomax = in;etc. Assignment puts the value on the right into the variable on the left.