【发布时间】:2018-07-10 09:33:38
【问题描述】:
该程序相当简单,我只是一个测试 try-catch 语句的初学者,尽管我已经阅读了 2 天,但我仍然无法理解为什么这个特定的 try 语句对我不起作用。我知道我可以使用 String 而不是 int,但我想知道为什么它对此不起作用,以及如何使它起作用。 本质上我希望用户输入 1 或 2,如果他们输入 1,程序(测验)将开始,否则如果他们按 2,程序将终止。如果他们按其他任何东西,例如一个字母,另一个数字,或试图做任何其他事情,它会说“再试一次”并重复相同的循环。
这似乎是一个愚蠢的问题,但我对此很陌生,如果能提供一些清晰的信息,我将不胜感激。
Scanner scanner = new Scanner(System.in);
int score = 0;
System.out.println("Are you ready for a quiz?\n1.yes\n2.no");
int input = scanner.nextInt();
do {
scanner.nextInt();
try {
if (input == 2) {
System.out.println("Maybe next time!");
System.exit(0);
} else if (input == 1) {
System.out.println("Okay! good luck!\n");
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Try again\n");
}
} while (input != 1);
【问题讨论】:
-
try/catch 块中的任何内容都不会抛出
InputMismatchException。 -
您需要将
nextInt调用移入try块,因为nextInt可能会引发异常。 (或者,使用hasNextInt主动检查,而不是被动地捕获异常。) -
你不需要 try catch,只需要一个额外的 else 块
标签: java