不适用于 Try/Catch 语句的 While 循环 [英] While loop that is not working with Try/Catch statements

查看:37
本文介绍了不适用于 Try/Catch 语句的 While 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让用户有机会在引入产生错误的东西后重复输入但有些东西不起作用,因为一旦 err 被捕获,try 的东西不会再次执行,而是它直接进入生成一个永恒圆环的捕获物.这是我的代码:

Im trying to give the user the opportunity to repeat an input after introducing something that has produced an error but something is not working because once the err is caught the try stuff is not executed again, instead it goes directly to the catch stuff generating an eternal cicle. Here is my code:

while (err==1){
    err=0;
    try{
        dim = keyboard.nextInt();
    } catch(Exception e){
        System.out.println("Oops! What you entered is not an integer.");
        err=1;
    }
}

推荐答案

当您输入一个非整数时,ScannernextInt() 的调用不会消耗非整数.您需要调用 keyboard.next()(或 keyboard.nextLine())来使用它.类似的东西,

When you enter a non-integer the Scanner call to nextInt() doesn't consume the non-integer. You need to call keyboard.next() (or keyboard.nextLine()) to consume it. Something like,

try {
    dim = keyboard.nextInt();
} catch (Exception e) {
    System.out.printf("%s is not an integer.%n", keyboard.next());
    err = 1;
}

这篇关于不适用于 Try/Catch 语句的 While 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆