Java 第二个catch在while循环中继续执行(Try catch)
我怎样才能解决它 为什么第二个catch一直在输出控制台中打印 我只是想打印一次,如果布尔数据类型不是真的,那么再次返回循环Java 第二个catch在while循环中继续执行(Try catch),java,try-catch,Java,Try Catch,我怎样才能解决它 为什么第二个catch一直在输出控制台中打印 我只是想打印一次,如果布尔数据类型不是真的,那么再次返回循环 Scanner input=new Scanner(System.in); int a ,b,result; boolean status=false; while(!status){ try{ a=input.nextInt(); b=input.nextInt(); resu
Scanner input=new Scanner(System.in);
int a ,b,result;
boolean status=false;
while(!status){
try{
a=input.nextInt();
b=input.nextInt();
result=a/b;
status=true;
}catch (ArithmeticException ex){
System.out.println(ex.getMessage());
}catch(InputMismatchException ex){
System.out.println(ex);
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}
请检查我的在线评论
while(!status){
try{
a=input.nextInt();
b=input.nextInt();
result=a/b;
status=true;
}catch (ArithmeticException ex){
System.out.println(ex.getMessage());
}catch(InputMismatchException ex){
System.out.println(ex);
input.next(); // So when ever InputMismatchException occurs Scanner will not consume the token it will keep that token so we need to consume that by using `next()`
}catch(Exception ex){
System.out.println(ex.getMessage());
}
在catch块中添加break语句,您可以使用它来获取所有不匹配的输入
catch(InputMismatchException ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
break;
}
您必须使用非
int
的输入。在catch
块中添加input.nextLine()
。@ElliottFrisch这不是一个答案吗?请注意,这会更好,因为他需要无限时间从扫描仪获取输入,但在您的代码中,在您给出有效输入后,它会一直退出。。。循环仍然存在。我假设他试图从用户那里获得无限时间的输入