while循环不使用Try/Catch语句

1 java try-catch while-loop

我试图让用户有机会在介绍产生错误的东西之后重复输入但是有些东西不起作用,因为一旦错误被捕获,尝试的东西不会再次被执行,而是直接转到捕获的东西产生永恒cicle.这是我的代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ell*_*sch 5

当您输入非整数时,Scanner调用nextInt()不会消耗非整数.您需要调用keyboard.next()(或keyboard.nextLine())来使用它.就像是,

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