In this tutorial, we will discuss about exception in thread "main" java.util.InputMismatchException
.
Table of Contents
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package org.arpit.java2blog; import java.util.Scanner; public class ReadIntegerMain { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter any integer: "); // This method reads the integer from user int num = scanner.nextInt(); scanner.close(); // Displaying the integer System.out.println("The Integer provided by user: "+num); } } |
If you put NA
as user input, you will get below exception.
Output:
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
.
Constructor of java.util.InputMismatchException
There are two constructors exist for java.util.InputMismatchException
- InputMismatchException(): Creates an InputMismatchException with null as its error message string.
- 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
.