我正在开发一个 Serpinski 三角形程序,该程序要求用户提供要绘制的三角形的级别。为了让我的程序更安全,我把它放在:
Scanner input= new Scanner(System.in);
System.out.println(msg);
try {
level= input.nextInt();
} catch (Exception e) {
System.out.print(warning);
//restart main method
}
如果用户输入了一个字母或符号,是否有可能在异常被捕获后重新启动 main 方法?
最佳答案
您可以使用 hasNextInt()
防止 Scanner
抛出 InputMismatchException
:
if (input.hasNextInt()) {
level = input.nextInt();
...
}
这是一个经常被遗忘的事实:您总是可以阻止 Scanner
在 nextXXX()
上抛出 InputMismatchException
> 首先确保 hasNextXXX()
。
但要回答您的问题,是的,您可以像调用任何其他方法一样调用 main(String[])
。
另见
- (Java) Opinion: Preventing Exceptions vs. Catching Exceptions
- How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
注意:要在循环中使用hasNextXXX()
,您必须跳过导致它返回false
的“垃圾”输入>。例如,您可以通过调用和丢弃 nextLine()
来做到这一点。
Scanner sc = new Scanner(System.in);
while (!sc.hasNextInt()) {
System.out.println("int, please!");
sc.nextLine(); // discard!
}
int i = sc.nextInt(); // guaranteed not to throw InputMismatchException
关于java - 捕获异常后是否可以调用 main(String[] args)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2758271/