我正在学习赫尔辛基大学 Java MOOC,有一个练习是创建一个程序,让您输入任意数量的数字,但只要您输入 0,程序就会结束并打印总数您所做的输入以及所有输入的总和。
我编写了代码,除了我将在下面解释的一个细节外,它按预期工作。这是我的代码:
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.");
}
}
}
问题是在输入 0 后,程序会同时执行 if
和 try
打印命令。所以程序以完全相同的顺序打印:
Input another number.
You have input a total of X numbers and the sum of all of them is X.
但它不允许您输入更多数字,因为程序以退出代码 0 结束。我希望它停止打印 Input another number.
我认为在 break
中添加一个 if
语句会自动结束循环,但由于某种原因,它会循环打印命令。我该如何解决这个问题?
答案 0 :(得分:2)
好吧,您的想法是正确的,但如果您希望循环在输入 0 后立即中断,则将 if
语句放在适当的位置,如下所示:
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.");
}
}