【发布时间】:2018-02-23 09:20:05
【问题描述】:
我对编程完全陌生,我遇到了一个问题,当我捕获 InputMismatchException 时,我无法返回到我的主 do while 循环。我搜索了谷歌,我无法找到并完全理解用户给出的解决方案。
我的目标是消除用户输入任何可能导致应用程序终止的字符的可能性。这就是为什么我用 try/catch 包围了几乎所有的代码。
我尝试在我的代码中添加更多循环,这一切都以两种方式结束:
- 在到达 catch 语句后,我的循环永远不会结束。
- 我被放回控制台,但没有任何反应(我仍然可以在那里输入)。
谁能解释我如何达到我的目标?我也试过 hasNextInt 希望它会再次要求我输入正确的值,但它没有。我究竟做错了什么?我调试了应用程序,我可以看到该过程从 while 跳过到我的代码末尾。
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);
【问题讨论】:
标签: java loops exception try-catch do-while