Tag Archives: java.util.InputMismatchException

[Solved] java.util.InputMismatchException


Pre-requisite :  Java : Scanner : User input, Parsing and File Reading
Below scanner file reading example throwing “java.util.InputMismatchException” because using scanner.next(regex) but some words in test data  not matching regex “\W” for word as in “Sr. project Lead” in given example.

Test data in file


Saurabh Gupta 36 "Sr project Lead" Noida
Sailesh
Nagar 34 "Project Lead"

Example

package scanner;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerToReadInputFromFile {
	public static void main(String[] args) {
	try {
		// Decalare Scanner and intialize with File input object
		Scanner sc = new Scanner(
		new File("C:\\Users\\Saurabh Gupta\\Desktop\\Data.txt"));
		while (sc.hasNextLine()) {
		   //System.out.println(sc.next(Pattern.compile("\\w+")));
			}
		} catch (FileNotFoundException ex) {
		    ex.printStackTrace();
		}
	}
}

Output


Saurabh
Gupta
36
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at scanner.ScannerToReadInputFromFile.main(ScannerToReadInputFromFile.java:17)

Solution
Always handle exception while using regular expressions. In this example pattern is not matching for ‘Sr Project Lead’ because word pattern allow on [A-Za-z0-1] char only.

[Solved]java.util.InputMismatchException


java.util.InputMismatchException which throw by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

  • InputMismatchException is runtime unchecked exception.
  • InputMismatchException is sub class of NoSuchElementException.

Constructors

  • InputMismatchException() : Constructs an InputMismatchException with null as its error message string.
  • InputMismatchException(String s): Constructs an InputMismatchException, saving a reference to the error message string s for later retrieval by the getMessage method.

Example

In below example create this java.util.InputMismatchException by passing some others type values other than expectation. For Example : age expected as integer value from console while passing as decimal value.

import java.util.Scanner;

public class JavaScannerExample {

	public static void main(String[] args) {
		// Create a Scanner object
		Scanner scanner = new Scanner(System.in); 

		try
		{
		//User different type of input from console
		System.out.println("Please enter user name:");
		String userName = scanner.nextLine();
		System.out.println("Please enter age:");
		int age = scanner.nextInt();
		System.out.println("Please enter salary:");
	    double salary = scanner.nextDouble();

	    //Output input by user
	    System.out.println("User Name: " + userName);
	    System.out.println("Age: " + age);
	    System.out.println("Salary: " + salary);
		}
		catch(Exception ex)
		{
			System.err.println("Entered user input are not match with required type:");
			ex.printStackTrace();
		}

	}

}
Please enter user name:
Saurabh Gupta
Please enter age:
13.5
Entered user input are not match with required type:
java.util.InputMismatchException
	at java.util.Scanner.throwFor(Unknown Source)
	at java.util.Scanner.next(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)
	at java.util.Scanner.nextInt(Unknown Source)
	at com.userinput.JavaScannerExample.main(JavaScannerExample.java:28)

Solution

  • In such type scenarios where user interaction required always write code and ask input as scanner.nextLine();
  • Always validate values type before assign to variable.
  • If any mismatch found and throw above exception show message to insert value again as required format.

References

https://docs.oracle.com/javase/8/docs/api/java/util/InputMismatchException.html

Know More

To know more about Java Exception Hierarchy, in-built exception , checked exception, unchecked exceptions and solutions. You can learn about Exception Handling in override methods and lots more. You can follow below links:  s