0

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
3

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

Comments

0
number = input.nextInt();

The line above reads an integer. The exception means you're inputting something that is something else (e.g. String, double)

Note: if you want to read any number, replace that line with:

number = input.nextDouble();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.