Java Arena
Step 4 of 5

Summing in a loop

Summing works like counting, but instead of adding one each time, the loop adds the value it read. The sum starts at 0 before the loop:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int total = 0;
        while (true) {
            int price = Integer.valueOf(scanner.nextLine());
            if (price == 0) {
                break;
            }
            total += price;
        }
        System.out.println("To pay: " + total);
    }
}
Input
4
12
3
0
Output
To pay: 19

total += price is shorthand for total = total + price. The other operators have one too: -=, *= and /=.

A loop can keep several of these at once, such as a count and a sum, each in its own variable made before the loop.

Your task

Challenge 1 of 3

Read the lengths of your runs in kilometres until 0, and print the total distance. For the input 5, 10, 8 and 0 the program prints:

Total: 23 km

Challenge 2

Read donations until 0. Print how many donations there were and their total. For the input 20, 5, 50 and 0 the program prints:

3 donations, 75 in total

Challenge 3

Read the money moving in and out of an account until 0. Positive amounts are income, negative amounts are spending. Print the income and the spending, the spending as a positive number. For the input 500, -40, -15 and 0 the program prints:

Income: 500
Spending: 55