我有這個try/catch包裹在do/while循環中,因爲在try/catch引發錯誤消息之後,我想讓它循環回到頂部。我嘗試過/同時,而且,我試着將代碼中的while循環放置在不同的地方,但沒有任何效果。該程序工作正常,直到拋出異常,然後進入無限循環。顯示錯誤信息後,我只想讓它循環回到頂部。如何在Java中無限循環地停止循環?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Integer userInput;
do {
try{
System.out.print("Enter a number? \n");
userInput = input.nextInt();
if (userInput == 1)
Animal1.displayMessage();//Display the total
if(userInput == 2)
Animal2.displayMessage();//Display the total
}
catch (Exception e) {
System.out.println(" That's not right ");
break;
}
} while (true);
}
}
這是顯示錯誤消息後它做什麼。
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
That's not right
Enter a number?
Enter a number?
如果我不停止它,它會繼續下去。
我有很多無限循環,我自己。我應該努力讓他們更確定。 – markspace
正如你所描述的,這適用於我。 –
我剛測試過你的代碼。如果輸入數字,它將無限循環,但如果輸入任何其他輸入,它會像應該那樣終止循環。 –