This question already has answers here:
Closed 4 years ago.
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;
}
}
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();