June 28, 2022

InputMismatchException in Java and Resolution

In this post we’ll discuss about java.util.InputMismatchException and how to fix it. InputMismatchException is thrown when you are trying to read tokens through a Scanner class instance and the input retrieved doesn’t match the pattern for the expected type.

InputMismatchException in Java

Scanner class in Java can be used to read input from a File, InputStream, Path or String. Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. These tokens may then be converted into values of different types using the various next methods. For example some of the next methods in the Scanner class for reading the next input of the corresponding data type are- nextLong(), nextBoolean(), nextByte(), nextDouble(), nextFloat(), nextInt().

When you are reading input using a Scanner class using one of the next method but the type of the passed input doesn’t match the next method used to get the input, InputMismatchException is thrown. This exception is also thrown if the input is out of range. For example if the passed input is of type String and you try to read it using nextInt() method then the InputMismatchException is thrown.

Java InputMismatchException Example

In the example you take input from the user and then display whether the passed integer is even or odd. Scanner class is used to take user input.

import java.util.Scanner;

public class InputMismatchExp {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a number: ");
    int i = sc.nextInt();
    if(i%2 == 0) {
      System.out.println("Entered number is even");
    }else {
      System.out.println("Entered number is odd");
    }
  }
}

Now if you pass the input as any other type like String, then InputMismatchException will be thrown.

Enter a number: 
Two
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 com.knpcode.programs.InputMismatchExp.main(InputMismatchExp.java:10)

How to resolve InputMismatchException

Only way to handle InputMismatchException is to ensure that passed input values are of compatible type.

That's all for the topic InputMismatchException in Java and Resolution. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment