×

InputMismatchException in Java

What is InputMismatchException?

One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is a subtype of both java.lang.Throwable and java.lang.Object, it offers every method that is offered by those types.

In other words, it is defined that A Scanner object will throw an InputMismatchException runtime exception Java if a token it has retrieved doesn't really match the criteria for the expected type or is beyond the expected type's range.InputMismatchException does not need to be stated in the throws section of a method or function Object()  because it is an unchecked exception.

Why Do InputMismatchExceptions Occur?

When utilizing Java programs that employ the Scanner class to prompt users for input, the InputMismatchException frequently occurs. When the data is incorrect for the intended type, an exception may occur. The input is either outside of the acceptable range or does not follow the template for the intended type.

An InputMismatchException is raised, for instance, when a user enters a String value when a program expects an Integer value.

When is an InputMismatchException raised?

The Scanner raises this unchecked exception to show that the returned token does not fit the pattern for the intended type or that it is beyond the expected type's range.

A Scanner is offered by java.utilpackage.a class that accepts user-provided text and rudimentary data types as input. In Java, it is the easiest technique of reading user input. When a user provides an incorrect type of input or input that is outside of the acceptable range, the InputMismatchException occurs.Simply, when the input type is incorrect, we receive the InputMismatchException. The Scanner throws the InputMismatchException when given a float value as input when it is expecting an integer.The Scanner will indeed throw the InputMismatchException if we supply a big integer value as input when the Scanner requires an integer.

How to Resist InputMismatchException?

In Java, avoiding InputMismatchException is fairly easy. There is only one easy way to prevent this exception: give the scanner valid input (either data of a similar type or data that should fall within an expected data type range).

Fixing InputMismatchException

It is important to make sure that inputs for a Scanner object belong to the right type and are acceptable for the expected type in order to prevent the InputMismatchException. If an exception is raised, the input data's format needs to be examined and corrected in order for the program to function properly.

  • InputMismatchException offers every method that the java.lang.Throwable and java.lang.Object classes offer because it is a subclass of each of them.

java.lang.Throwable class methods

addSuppressed()

fillInStackTrace()

getCause()

getLocalizedMessage()

getMessage()

getStackTrace()

getSuppressed()

initCause()

printStackTrace()

printStackTrace()

printStackTrace()

setStackTrace()

toString().

Java.lang.Object class methods

clone()

equals()

finalize()

getClass()

hashCode()

notify()

notifyAll()

wait().

Constructors of InputMismatchException?

  • Public InputMismatchException() 

creates an InputMismatchException with the error string null.

  • Public InputMismatchException(String s)

It creates an InputMismatchException and stores a pointer to the error message string s for retrieval by the getMessage function.

Arguments:The detailed message is s.

Examples of InputMismatchException

Example 1

import java.util.Scanner;
public class InputMismatchExceptionExample
 {
    public static void main(String[] args)
 {
        Scanner scanner = new Scanner(System.in);
System.out.println("Enter an integer: ");


        int integer = scanner.nextInt();
scanner.close();


System.out.println("You entered: " + integer);
    }
}

The output of the program

java -cp /tmp/pCdDCZnKjBInputMismatchExceptionExample
Enter an integer: 
4
You entered: 4

Example 2

import java.util.Scanner;
public class EmployeeData
{
   int salary;
   String name;
   public EmployeeData(String name, int salary)
   {
this.salary = salary;
      this.name = name;
   }
   public void display() {
System.out.println("Name of the Employee is: "+name);
System.out.println("salary of the Employee is: "+salary);
   }
   public static void main (String args[])
   {
      Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
      String name = sc.next();
System.out.println("Enter your salary: ");
      int salary = sc.nextInt();
EmployeeDataobj = new EmployeeData(name, salary);
obj.display();
   }
}

The output of the program

Enter your salary:

Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at EmployeeData.main(EmployeeData.java:21)
Enter your name: sravani


Enter your salary: 20000


Name of the Employee is: avanisalary of the Employee is: 0

Example 3

import java.util.InputMismatchException;
import java.util.Scanner;
public class Solution
{  
   public static void main(String[] args)
   {
      Scanner sc = new Scanner(System.in);
         try {
System.out.println("Enter the Value: ");
            Integer inputInt = sc.nextInt(); 
System.out.println(inputInt);
         } 
         catch (InputMismatchException ex) 
{
System.out.println("We have given input as float expecting integer "+ ex);
         }
   }
}

The output of the program

Enter the Value: 
1.6
We have given input as float expecting integer java.util.InputMismatchException

Related Topics

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Short Circuit Logical Operators in Java

When there are two or more relational expressions in a decision-making statement, logical operators are utilized to combine them. The logical operators short circuit and not-short circuit fall into two...

5 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Diamond problem in Java

The Diamond Problem in Java is connected to multiple inheritances. It is also referred to as the "deadly diamond dilemma" or even the "deadly diamond of death”. The solution for...

5 minutes read.

Java Full Stack

A person who can create both the front end and back end of an application is a full-stack developer. In essence, the term "Java full-stack" refers to a web developer...

9 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Enhanced For Loop (For-each Loop)

JAVA ENHANCED FOR LOOP The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through...

4 minutes read.

Facts about null in Java

Nearly all programming languages have a relationship with null. Hardly any programmers are unconcerned by null. The null has a java.lang.NullPointerException association in Java. Given that it is a class...

4 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.