[英]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.