while try catch无限循环

   
Scanner console= new Scanner(System.in); 
 private int CatchInput() {
while (true) {
try {
System.out.println("------输入id------");
return console.nextInt();
} catch (InputMismatchException e) {
System.out.println("------输入错误------");
}
}
}
当console类型输入错误 执行catch语句 通过while循环重新执行try语句 会使用上一次的结果直接进入catch 以此往复无限循环


 
 private int CatchInput() {
while (true) {
try {
          Scanner console= new Scanner(System.in);  
                System.out.println("------输入id------");
return console.nextInt();
} catch (InputMismatchException e) {
System.out.println("------输入错误------");
}
}
}
将Scanner的定义放入try语句中即可

猜你喜欢

转载自www.cnblogs.com/xiumumi/p/10094571.html