[英]While loop keeps executing a command after a break statement
我正在做赫爾辛基大學 Java MOOC 的練習,其中包括創建一個程序,該程序可以讓您輸入任意數量的數字,但是一旦您輸入 0,程序就會結束並打印您輸入的總數did 和所有這些的總和。
我編寫了代碼,除了我將在下面解釋的一個細節外,它按預期工作。 這是我的代碼:
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
one 中添加一個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.");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.