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 callingnext()
ornextLine()
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