while 循环在 break 语句后继续执行命令
While loop keeps executing a command after a break statement
我正在学习赫尔辛基大学 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.
我认为在 if
中添加一条 break
语句会自动结束循环,但由于某种原因它会循环打印命令。我该如何解决这个问题?
好吧,你的想法是对的,但是如果你希望循环在输入 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.");
}
}
我正在学习赫尔辛基大学 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.
我认为在 if
中添加一条 break
语句会自动结束循环,但由于某种原因它会循环打印命令。我该如何解决这个问题?
好吧,你的想法是对的,但是如果你希望循环在输入 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.");
}
}