javavalidationexceptionwhile-loop

How to properly use a try/catch block in a while loop to handle invalid input in Java?


I’m trying to write a Java program that asks the user to input a positive integer inside a while loop. The loop should continue until valid input is provided.

I’ve tried using a try/catch block to handle invalid inputs like strings, but I’m still running into issues. For example:

Here’s the code I’ve written so far:

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int userInput = -1;

        while (userInput < 0) {
            try {
                System.out.print("Enter a positive number: ");
                userInput = scanner.nextInt(); // Crashes if invalid input is entered
            } catch (InputMismatchException e) {
                System.out.println("Invalid input. Please enter a valid number.");
                scanner.nextLine(); // Attempt to clear the buffer, but it doesn't work
            }
        }

        System.out.println("You entered: " + userInput);
        scanner.close();
    }
}

The issue:

  1. When invalid input (like a string) is entered, the program skips re-prompting the user.

  2. I suspect there’s an issue with how I’m clearing the input buffer using scanner.nextLine().

What I’ve tried:

  1. Wrapping the scanner.nextInt() inside a try/catch block to catch the exception.

  2. Using scanner.nextLine() after catching the exception to clear the input.

My question:

How can I properly handle invalid input in this scenario so that the program keeps re-prompting the user until a valid positive integer is provided?


Solution

  • Perhaps try something like:

    String userInput = "";
    
    while (true) {  // loop until valid input 
      userInput = scanner.nextLine();
      if (isInteger(userInput)) 
        break;
      System.out.print("Please enter a valid number.");
    }
      
    private static boolean isInteger(String str) {
      try {
        Integer.parseInt(str); 
        return true;
      } catch(NumberFormatException e) {
        return false;
      }
    

    These previous answers may also help: https://stackoverflow.com/a/53904761/6423542 https://stackoverflow.com/a/24836513/6423542