christina.morales
christina.morales 1d ago β€’ 0 views

How to fix InputMismatchException with Scanner in Java

Hey everyone! πŸ‘‹ I'm struggling with `InputMismatchException` in my Java code when using `Scanner`. It keeps crashing when I enter the wrong type of input. Any tips on how to fix this? πŸ€”
πŸ’» Computer Science & Technology

1 Answers

βœ… Best Answer
User Avatar
corey.escobar Jan 3, 2026

πŸ“š Understanding InputMismatchException

The InputMismatchException in Java is a runtime exception that occurs when the Scanner class tries to read an input that doesn't match the expected data type. For example, if your code expects an integer but the user enters a string, this exception is thrown. It's crucial to handle this exception gracefully to prevent your program from crashing and to provide a better user experience.

πŸ“œ History and Background

The Scanner class was introduced in Java 5 (JDK 1.5) as a way to parse primitive types and strings from various input sources, such as the keyboard (System.in), files, and strings. Before Scanner, handling user input was more cumbersome, often involving BufferedReader and manual parsing. The InputMismatchException is part of the standard Java library and has been a common issue for Java developers since its introduction.

πŸ”‘ Key Principles to Fixing InputMismatchException

  • πŸ” Input Validation: Always validate user input before processing it. Check if the input matches the expected data type.
  • πŸ›‘οΈ Exception Handling: Use try-catch blocks to catch the InputMismatchException and handle it gracefully.
  • βœ… Scanner Methods: Utilize Scanner methods like hasNextInt(), hasNextDouble(), etc., to check the type of the next input before reading it.
  • πŸ’¬ Clear Prompts: Provide clear and specific prompts to the user to guide them in entering the correct type of input.
  • πŸ”„ Retry Mechanism: Implement a loop that prompts the user for input again if an InputMismatchException occurs.
  • 🧹 Clear the Buffer: After catching the exception, clear the invalid input from the Scanner's buffer using next() to avoid an infinite loop.
  • πŸ’‘ Logging: Log the exception details for debugging purposes.

πŸ’» Real-world Examples

Here are a few examples illustrating how to handle InputMismatchException:

Example 1: Reading an Integer


import java.util.Scanner;

public class InputMismatchExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number;

        try {
            System.out.print("Enter an integer: ");
            number = scanner.nextInt();
            System.out.println("You entered: " + number);
        } catch (java.util.InputMismatchException e) {
            System.out.println("Invalid input. Please enter an integer.");
            scanner.next(); // Clear the invalid input from the buffer
        }
        scanner.close();
    }
}

Example 2: Using hasNextInt() for Validation


import java.util.Scanner;

public class InputMismatchExample2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number = 0;
        boolean isValidInput = false;

        while (!isValidInput) {
            System.out.print("Enter an integer: ");
            if (scanner.hasNextInt()) {
                number = scanner.nextInt();
                isValidInput = true;
            } else {
                System.out.println("Invalid input. Please enter an integer.");
                scanner.next(); // Clear the invalid input from the buffer
            }
        }

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

Example 3: Reading Multiple Inputs


import java.util.Scanner;

public class InputMismatchExample3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("Enter an integer and a double (separated by space): ");
            int integerValue = scanner.nextInt();
            double doubleValue = scanner.nextDouble();

            System.out.println("Integer: " + integerValue);
            System.out.println("Double: " + doubleValue);
        } catch (java.util.InputMismatchException e) {
            System.out.println("Invalid input. Please enter an integer and a double.");
            scanner.next(); // Clear the buffer
        } finally {
            scanner.close();
        }
    }
}

πŸ§ͺ Practice Quiz

  1. ❓ What type of exception is InputMismatchException?
  2. πŸ› οΈ How can you prevent InputMismatchException from occurring?
  3. πŸ’‘ What method can you use to check if the next input is an integer?
  4. πŸ“ What should you do after catching an InputMismatchException to avoid an infinite loop?
  5. πŸ”’ Why is it important to handle InputMismatchException?

πŸŽ“ Conclusion

Handling InputMismatchException is a fundamental aspect of writing robust Java applications that involve user input. By using input validation, exception handling, and appropriate Scanner methods, you can create programs that gracefully handle unexpected input and provide a better user experience. Always remember to clear the Scanner buffer after catching the exception to prevent infinite loops.

Join the discussion

Please log in to post your answer.

Log In

Earn 2 Points for answering. If your answer is selected as the best, you'll get +20 Points! πŸš€