Site icon TestingDocs.com

How to fix java.util.InputMismatchException

Overview

InputMismatchException is a common exception when we work with Java programs that prompts and take input from the user. As the exception name indicates the input doesn’t match with the program expectations for the data.

The root cause

We get this error when the user enters the input that mismatches with the expected datatype of the input variable in the program. Let’s say the program expects a double value and the user enters a String value.

 

 

Stack Trace of InputMismatchException

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 Demo.main(Demo.java:16)

 

Scanner class throws this exception.

Screenshot

Fix is to handle the exception and let the user know about the error in the input. In the below example, the code is wrapped with a try – catch block. So, if the code throws the exception the catch handler is invoked to notify the user with a user- friendly message. 

If the user enters a valid data for the radius then the catch block would not be executed. This is because the code doesn’t throw the exception when the input is valid.


Java Listing

import java.util.InputMismatchException;
import java.util.Scanner;
/**************************************************
 * Demo.java
 * @program   	: 
 * @web        	: www.TestingDocs.com
 * @author      :  
 * @version     : 1.0
 **************************************************/
public class Demo {
  //main
  public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    double radius=0.0;
    double areaCircle=0.0;

    try {
      System.out.println("Enter Radius := ");
      radius = keyboard.nextDouble();
      areaCircle = Math.PI*radius*radius;
      System.out.println("Area of Circle = "+ areaCircle);
      keyboard.close();
    }catch(InputMismatchException ime) {
      System.out.println("Please enter valid number for radius");
    }
  } // end main
} // end Demo

 

Sample run output

Enter Radius :=
zzz
Please enter valid number for radius

The string ‘zzz’ is invalid data for radius with double datatype. The code in the try block throws an exception. The catch block handle it and displays a message to the user. 

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/


For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version