我该如何解决???
为什么第二个catch在输出控制台中继续打印...
我只是想打印一次,然后如果布尔数据类型不正确,则再次返回循环。
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());
}
}
}
答案 0 :(得分:0)
请检查我的在线评论
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());
}
答案 1 :(得分:0)
在catch块中添加break语句,该语句用于获取所有不匹配输入
catch(InputMismatchException ex){
ex.printStackTrace();
System.out.println(ex.getMessage());
break;
}