I'm doing the University of Helsinki Java MOOC and there's an exercise that consists in creating a program that lets you input as much numbers as you want, but as soon as you input a 0 the program ends and prints the total number of inputs you did and the sum of all of them.
I wrote the code and it works as intended except for one detail that I'll explain bellow. Here's my code:
public class Application {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input a number.");
int totalNumbers = 0;
int sum = 0;
while (true) {
try {
int input = Integer.parseInt(scanner.nextLine());
sum += input;
totalNumbers = totalNumbers + 1;
System.out.println("Input another number.");
if (input == 0) {
System.out.println("You have input a total of " + totalNumbers + " numbers and the sum of all of them is " + sum + ".");
break;
}
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}
}
The issue is that after inputting 0 the program executes both the if
and the try
print commands. So the program prints, in this exact same order:
Input another number.
You have input a total of X numbers and the sum of all of them is X.
But it doesnt let you input more numbers because the program ends with exit code 0. I want it to stop printing Input another number.
I thought that adding a break
statement inside the if
one would automatically end the loop, but for some reason it loops the print command. How can I solve this?
Well You have the right idea but if u want the loop to break immediately after inputting a 0 then place your if
statement at the appropriate place like so:
while (true) {
try {
int input = Integer.parseInt(scanner.nextLine());
if (input == 0) {
System.out.println("You have input a total of " + totalNumbers + " numbers and the sum of all of them is " + sum + ".");
break;
}
sum += input;
totalNumbers = totalNumbers + 1;
System.out.println("Input another number.");
}
catch (NumberFormatException e) {
System.out.println("Please input a valid number.");
}
}