我不知道为什么try catch语句不起作用:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
protected static int intNum;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("[Shopping List] This is the shopping list GUI by Endercy.");
System.out.println("[Shopping List] Controls are here:");
System.out.println("[Shopping List] Type 1 to create a Shopping List");
System.out.println("[Shopping List] Type 2 to enter a Shopping List name to view its contents");
System.out.println("[Shopping List] Type 3 Add an item to your shopping list");
System.out.println("[Shopping List] Type 4 to remove an item from your shopping list");
System.out.println("[Shopping List] Type 5 to add a price to one of your items in your shopping list");
intNum = scanner.nextInt();
switch(intNum) {
case 1:
System.out.println("test");
break;
case 2:
System.out.println("test test");
break;
case 3:
System.out.println("test test test");
break;
case 4:
System.out.println("test test test test");
break;
case 5:
System.out.println("test test test test test");
break;
default:
while(true) {
System.out.println("I'm sorry, but this number is not on our controls list. Try again!");
try {
intNum = scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid Number, try again!");
intNum = scanner.nextInt();
}
switch(intNum) {
case 1:
System.out.println("test");
break;
case 2:
System.out.println("test test");
break;
case 3:
System.out.println("test test test");
break;
case 4:
System.out.println("test test test test");
break;
case 5:
System.out.println("test test test test test");
break;
}
}
}
break;
}
System.out.println("Thanks for trying out this thingy");
}
}
这是代码,如果有人输入诸如283479234729472472983472984723或字符串等无效内容,我只想执行InputMismatchException。
但是当我运行它时,我输入类似的内容,它不允许我使用扫描仪再试一次,只是跳到:
Exception in thread "main" java.util.InputMismatchException: For input string: "879857294729847917412942472394724237492734923"
at java.base/java.util.Scanner.nextInt(Scanner.java:2264)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at com.endercy.challenges.java.arraylist.shoppinglist.Main.main(Main.java:19)
它并不能让我输入另一个。
答案 0 :(得分:0)
您应该将另一个try catch blok放入第一个scan.nextInt方法。我认为代码不会在那里传递并在其中引发异常