0
我完全是編程的新手,我遇到了一個問題,當我捕獲InputMismatchException時,無法返回到主循環。我搜索了Google,但無法找到並完全理解用戶提供的解決方案。如何在異常捕獲後延長do ... while循環
我的目標是消除用戶輸入任何可能導致應用程序終止的字符的可能性。這就是爲什麼我用try/catch包圍幾乎所有的代碼。
我試圖把更多的循環,以我的代碼,而這一切都在2種方式結束:
- 我環路到達catch語句後無法完成。
- 我放回到控制檯,什麼也沒有發生(我仍然可以在那裏鍵入)。
有人能解釋我的如何達到我的目標嗎?我也試過hasNextInt希望它會再次要求我輸入適當的值,但它不會。我究竟做錯了什麼?我調試了應用程序,我可以看到的是該過程從我的代碼結束時跳過。
Scanner scanner = new Scanner(System.in);
System.out.print("\nChoose mode: ");
int userInput = 0;
do {
do {
try {
userInput = scanner.nextInt();
switch (userInput) {
case 1:
Mode_1.multiplyTwoInteger();
break;
case 2:
Mode_2.multiplyTwoSpecifiedValues();
break;
case 3:
System.out.println("\nYou quit application. Goodbye :)");
return;
default:
System.out.print("Not found! Choose again game mode: ");
}
} catch (Exception InputMismatchException) {
System.out.print("Wrong input!\nChoose again:");
}
} while (userInput <= 0 || userInput > 3);
} while (userInput != 3);
這就是新的知識給我。我不知道它是這樣工作的。非常感謝您的解決方案。 – Ahlen