java - Try and catch 语句不会让我再试一次
问题描述
我不知道为什么 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");
}
}
这是代码,我只想做 InputMismatchException 以防有人输入无效的东西,如 283479234729472983472984723 或字符串等。
但是当我运行它时,我输入了类似的东西它不允许我用扫描仪再次尝试它只是跳到:
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)
它不让我进入另一个。
解决方案
您应该在第一个scanner.nextInt 方法中放置另一个try catch 块。我认为代码没有通过那里并在那里引发异常
推荐阅读
- git - 如果合并两个具有相同提交的分支会发生什么?
- c# - 为什么我必须继续在已经从父类继承的子类中添加 using 指令?
- java - 在 Java 中赋值后的内存分配
- python - 如何使 QListWidgetItem 根据其内容自动调整大小,并适合其 QListWidget
- java - 使用 Java-Stream 将字符串转换为 Map 并在结果 Map 中重复值
- c# - EPPlus:如何用静态值替换所有公式?
- c++ - 对任意数量的类使用可变参数模板参数
- python - 在 PIL 中调整图像大小时不了解此 ValueError 的原因
- mysql - MySql 是否有最大锁定超时设置
- reactjs - 如何在 React Native TextInput 中添加多色占位符文本?