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);
}
}
4
12
3
0To pay: 19total += 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.