Search code examples
javareplaceinputmismatchexception

Java - How to replace "java.util.InputMismatchException" error with something else


How do I make it so a "java.util.InputMismatchException" doesnt show?

For example:

import java.util.Scanner;

class Test {
  public static void main(String args[]){

    Scanner input = new Scanner(System.in);
    int number;

    System.out.print("Type a number: ");
    number = input.nextInt();
    System.out.println(number);

    input.close();
  }
}

It works fine when you type in a valid int, like "5", but when the user type an invalid int, like "5.1" or "a", it will give the error Exception in thread "main" java.util.InputMismatchException. Is there a way to bypass the error and display/do something else if the user types in a non-valid int?

Like so:

Type in a number: a
That is not a valid number. Try again

Solution

  • First, you can catch the exception and do something you want.

    A better way is use Scanner.hasNextInt() to test whether the line user input is a int.

    System.out.println("Type a number");
    while(!input.hasNextInt()) {
        input.nextLine();
        System.out.println("That is not a valid number. Try again");
    }
    number = input.nextInt();