使用try-catch和while循环捕获时出错

时间:2015-07-05 16:51:13

标签: java loops while-loop

我试图确保用户输入是一个整数,但是当我使用下面的代码时,我只得到print语句的无限循环。有关如何改进的任何建议吗?

boolean valid = false;
System.out.println("What block are you gathering? (use minecraft block ids)");
while(valid == false){
    try{
        block = input.nextInt();
        valid = true;
    }
    catch(InputMismatchException exception){
        System.out.println("What block are you gathering? (use minecraft block ids)");
        valid = false;
    }
}

1 个答案:

答案 0 :(得分:2)

nextInt()不会消耗无效输入,因此会一遍又一遍地尝试读取相同的无效值。要解决此问题,您需要通过调用接受任何值的next()nextLine()来明确使用它。

BTW为了让您的代码更清晰,并避免像创建异常这样的昂贵操作,您应该使用hasNextInt()等方法。

以下是如何整理代码

System.out.println("What block are you gathering? (use minecraft block ids)");
while(!input.hasNextInt()){
    input.nextLine();// consume invalid values until end of line, 
                     // use next() if you want to consume them one by one.
    System.out.println("That is not integer. Please try again");
}
//here we are sure that next element will be int, so lets read it
block = input.nextInt();