Averages after the loop
An average needs both a sum and a count: it's the sum divided by the count. The loop collects the two, and the average is calculated after the loop, once all the numbers are in:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
while (true) {
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) {
break;
}
count++;
sum += number;
}
if (count == 0) {
System.out.println("No numbers");
} else {
double average = (double) sum / count;
System.out.println("Average: " + average);
}
}
}
4
5
8
0Average: 5.666666666666667Two details matter:
(double) sum / countturns the sum into adoublebefore dividing, so the decimals are kept (module 4 showed why).- With no numbers at all,
countis 0, and there's no average to show. Theifchecks for that before dividing.