Java Arena
Step 5 of 5

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);
        }
    }
}
Input
4
5
8
0
Output
Average: 5.666666666666667

Two details matter:

  • (double) sum / count turns the sum into a double before dividing, so the decimals are kept (module 4 showed why).
  • With no numbers at all, count is 0, and there's no average to show. The if checks for that before dividing.

Your task

Challenge 1 of 3

Read ratings from 1 to 5 until 0 (there's always at least one rating), and print their average. For the input 4, 5, 3 and 0 the program prints:

Average rating: 4.0

Challenge 2

Read temperatures until -999. Print the average of the ones above 0 as Average of warm days: X, or No warm days when there were none. For the input 12, -3, 7 and -999 the program prints:

Average of warm days: 9.5

Challenge 3

A survey collects answers, yes or no, until stop. Print the share of yes answers as a percentage, calculated as 100.0 times the yes answers divided by all answers. There's always at least one answer. For the input yes, yes, no, yes and stop the program prints:

75.0% said yes