0

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?

1 Answers1

0

So when a non integer is entered, the code immediately jumps to the exception block, because parser.nextInt() throws an exception. This exception causes the execution to jump over your assignment of valid=true straight to the catch block. Therefore, the while loop keeps on going because !valid is still true.

Maybe add System.exit() in your exception block.

Better would be to get the next character, test to see if it is valid. If valid exit the loop, if not valid display message. Also give them a character to press to stop trying. So that if they enter a pin or a 'exit' character you will stop.

Post your next try.

cogitoboy
  • 114
  • 1
  • 4
  • 1
    or discard (read and ignore) the wrong input - the apparent intention of the `while` loop is to iterate until a valid entry is done – user16320675 Apr 19 '22 at 16:04