Write a program in Java which reads in numbers from the keyboard, one per line, until it gets a zero. Then print out the number of values entered, the sum of all values, the largest number, the smallest number, and the average of all the numbers. Do not count the zero. (So, if you read in 1,6,7,4,0, the average is 4.5). Here is sample output from one version of the program:
% ./stats
2
4
6
12
-9
0
# items: 5
Sum: 15
Max: 12
Min: -9
Mean: 3
%
import java.util.Scanner;
public class stats {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in); // variables
int n = sc.nextInt();
int count = 0, smallest = n, largest = n, total = 0;
while(n != 0) // looping as long as number is not 0
{
count++; // counting items
if(smallest > n) // updating maximum
smallest = n;
if(largest < n) // updating minimum
largest = n;
total += n; // adding number to total
n = sc.nextInt(); // taking user input again
}
System.out.println("# items: " + count);
System.out.println("Sum: " + total);
System.out.println("Max: " + largest);
System.out.println("Min: " + smallest);
System.out.println("Mean: " + (total/(count*1.0)));
}
}
// Please up vote. Happy Learning!
Write a program in Java which reads in numbers from the keyboard, one per line, until...