Error catching with try-catch and while loop [dupl

2020-02-15 09:07发布

问题:

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