while循环不能使用Try / Catch语句 [英] While loop that is not working with Try/Catch statements

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

问题描述

我试图让用户有机会在介绍产生错误的内容之后重复输入但是某些内容无法正常工作,因为一旦错误被捕获,则尝试的内容不会再次执行,而是它直接进入产生永恒cicle的捕获物。这是我的代码:

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;
    }
}


推荐答案

你输入一个非整数扫描器调用 nextInt()不消耗非整数。您需要调用 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;
}

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

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