[Solved] Exception in thread “main” java.util.InputMismatchException

In this tutorial, we will discuss about exception in thread "main" java.util.InputMismatchException.

What causes java.util.InputMismatchException?

A Scanner throws this exception to indicate that the token retrieved does not match the expected type pattern, or that the token is out of range for the expected type.

In simpler terms, you will generally get this error when user input or file data do not match with expected type.

Let’s understand this with the help of simple example.

If you put NA as user input, you will get below exception.
Output:

Enter any integer: NA
Exception in thread “main” java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at org.arpit.java2blog.ReadIntegerMain.main(ReadIntegerMain.java:13)

As you can see, we are getting Exception in thread "main" java.util.InputMismatchException for input int because user input NA is String and does not match with expected input Integer.

Hierarchy of java.util.InputMismatchException

InputMismatchException extends NoSuchElementException which is used to denote that request element is not present.

NoSuchElementException class extends the RuntimeException, so it does not need to be declared on compile time.

Here is a diagram for hierarchy of java.util.InputMismatchException.

JAVA CODING INTERVIEW QUESTIONS

Constructor of java.util.InputMismatchException

There are two constructors exist for java.util.InputMismatchException

  1. InputMismatchException(): Creates an InputMismatchException with null as its error message string.
  2. InputMismatchException​(String s): Creates an InputMismatchException, saving a reference to the error message string s for succeeding retrieval by the getMessage() method.

How to solve java.util.InputMismatchException?

In order to fix this exception, you must verify the input data and you should fix it if you want application to proceed further correctly. This exception is generally caused due to bad data either in the file or user input.

That’s all about how to fix exception in thread "main" java.util.InputMismatchException.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.