Error catching with try-catch and while loop [duplicate]

梦想与她 提交于 2019-12-29 09:50:10

问题


I'm trying to make sure that the users input is an integer but when I use the below code I just get an infinite loop of the print statement. Any advice of how to improve?

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:


nextInt() doesn't consume invalid input so it will try read same invalid value over and over again. To solve this problem you need to consume it explicitly by calling next() or nextLine() which accept any value.

BTW to make your code cleaner and avoid expensive operations like creating exceptions you should use methods like hasNextInt() .

Here is how you can organize your code

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();


来源:https://stackoverflow.com/questions/31232745/error-catching-with-try-catch-and-while-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!