[英]Is it possible to call the main(String[] args) after catching an exception?
我正在开发一个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();
...
}
这是一个经常被遗忘的事实: 您始终可以通过首先确保hasNextXXX()
来阻止 Scanner
在nextXXX()
上抛出InputMismatchException
。
但是要回答您的问题,是的,您可以像调用其他任何方法一样调用main(String[])
。
注意 :要在循环中使用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
好了,您可以递归调用它: main(args)
,但是最好使用while
循环。
您最好这样做:
boolean loop = true;
Scanner input= new Scanner(System.in);
System.out.println(msg);
do{
try {
level= input.nextInt();
loop = false;
} catch (Exception e) {
System.out.print(warning);
//restart main method
loop = true;
}
while(loop);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.