[英]Why doesn't my try catch statement work?
該程序非常簡單,我只是測試try-catch語句的初學者,盡管我已經閱讀了兩天,但我仍然無法理解為什么這個特定的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);
1 。 問題是什么 ?
查看Invalid input. Try again
Invalid input. Try again
,必須在try
塊中引發InputMismatchException
,並且不會發生,因為輸入不會進入if
或else if
,可以完成您期望的操作
try {
if (input == 2) {
System.out.println("Maybe next time!");
System.exit(0);
} else if (input == 1) {
System.out.println("Okay! good luck!\n");
}else{
throw new InputMismatchException();
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Try again\n");
}
2 。 如何處理這種用法?
但是Exception
不必用作常規行為,並且要准備使用Strings
,您需要:
System.out.println("Are you ready for a quiz?\n1.yes\n2.no");
String input;
do {
input= scanner.nextLine();
if (input.equals("2")) {
System.out.println("Maybe next time!");
System.exit(0);
} else if (input.equals("1")) {
System.out.println("Okay! good luck!\n");
}else{
System.out.println("Invalid input. Try again\n");
}
} while (!input.equals("1"));
3 。 如何改善呢?
您可以更改某些print
的位置,因此可以簡化為:
System.out.println("Are you ready for a quiz?\n1.yes\n2.no");
String input;
do {
input= scanner.nextLine();
if (input.equals("2")) {
System.out.println("Maybe next time!");
System.exit(0);
}
System.out.println("Invalid input. Try again\n");
} while (!input.equals("1"));
System.out.println("Okay! good luck!\n");
我將int方法轉換為String。 我以為我只用一個int方法就可以達到同樣的目的,但我做不到。 謝謝大家,這是現在的工作方式:
enter code hereScanner scanner = new Scanner(System.in);
System.out.println("Are you ready for a quiz?\n1.yes\n2.no");
String input;
do {
input = scanner.nextLine();
if(input.equals("2")) {
System.out.println("Maybe next time!");
System.exit(0);
} else if (input.equals("1")) {
System.out.println("Okay! good luck!\n");
}
else { System.out.println("Invalid input. Try again\n");
}
} while (!input.equals("1"));
僅在try塊中拋出匹配異常時,才執行Catch塊。 在這種情況下,不會發生異常。
在else塊中拋出異常,您錯過了。 就像這樣,
try {
if (input == 2) {
System.out.println("Maybe next time!");
System.exit(0);
} else if (input == 1) {
System.out.println("Okay! good luck!\n");
}else{
throw new InputMismatchException();
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Try again\n");
}
您正在捕獲特定的異常,即InputMismatchException,但您的try塊沒有可引發此異常的代碼,要處理該情況,必須強制拋出該異常,以便您的catch塊可以處理該異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.