To avoid infinite loop when the exception is thrown, you must skip the current line and move on to the next line for processing. Currently, when the exception is thrown, you are re-iterating and scanning the same line which again throws exception and hence you are stuck in infinite loop.
I think you need to write the scan.nextLine()
method call when an exception is thrown.
catch (InputMismatchException e) // outputs error message if value provided is not an integer
{
System.out.println("Incorrect input type.");
// Moved the nextLine() method call over here
scan.nextLine();
}
Also modify the logic to detect if the number is 4 digit or not. Use integer comparison using<
and >
instead of converting the number into string.