I am writing a simple java console game. I use the scanner to read the input from the console. I am trying to verify that it I ask for an integer, I don’t get an error if a letter is entered. I tried this:
boolean validResponce = false;
int choice = 0;
while (!validResponce)
{
try
{
choice = stdin.nextInt();
validResponce = true;
}
catch (java.util.InputMismatchException ex)
{
System.out.println("I did not understand what you said. Try again: ");
}
}
but it seems to create an infinite loop, just printing out the catch block. What am I doing wrong.
And yes, I am new to Java
nextInt()won’t discard the mismatched output; the program will try to read it over and over again, failing each time. Use thehasNextInt()method to determine whether there’s anintavailable to be read before callingnextInt().Make sure that when you find something in the
InputStreamother than an integer you clear it withnextLine()becausehasNextInt()also doesn’t discard input, it just tests the next token in the input stream.