Jas*_*son 1 java exception-handling
我正在研究一个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
}
Run Code Online (Sandbox Code Playgroud)
如果用户用字母或符号打孔,是否有可能在捕获到异常后重新启动main方法?
你可以使用以下方法防止Scanner投掷:InputMismatchExceptionhasNextInt()
if (input.hasNextInt()) {
level = input.nextInt();
...
}
Run Code Online (Sandbox Code Playgroud)
这是一个经常被遗忘的事实:你总是可以防止一个Scanner从抛InputMismatchException上nextXXX()首先保证hasNextXXX().
但是回答你的问题,是的,你可以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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1955 次 |
| 最近记录: |