I'm a very beginner programmer, in my first year of college. Currently, I'm trying to write some Java code to have the user insert a pin number using a scanner, asking for a new input if the pin provided isn't an int. Here's what I've written:
System.out.println("Please enter your pin. Please note that only numbers are allowed for this selection.");
boolean valid = false;
while(!valid)
{
try
{
pin = parser.nextInt();
valid = true;
}
catch (InputMismatchException error)
{
System.out.println("Please use only numbers in your pin.");
}
}
This code asks for a pin, sets a boolean variable to false, and enters a while loop. A scanner object asks for an input from System.in, and if the response isn't an int, then the catch statement is entered, where an error message is printed. If the response is an int, then all is well, and the int is assigned to the pin field and we move on. The issue, however, is that when the catch statement is entered, it repeats infinitely. My intention with this code was that the catch statement would execute, the code would run back to the top of the while loop, and I would be able to use the try block again, giving a new input to be checked. However, the code seems to be skipping this new input step, simply going straight to the catch block on subsequent loops. Any ideas on how to fix this?