×

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

Applet Life Cycle in Java

In this article, we are going to acknowledge you about what a applet is, what is its life cycle and stages in life cycle, along with the syntax and example...

4 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Calculator Program in Java

Calculator Program in Java A calculator performs the basic mathematical operations such as addition, subtraction, multiplication, etc. In this section, we will create a calculator program in Java using switch case...

5 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

Graphics Program in Java

Graphics Program in Java The graphics program in Java is part of the Swing program in Java. In this section, we will learn about the implementation of custom graphics using some...

6 minutes 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.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

if-else Program in Java

if-else Program in Java The if-else program in Java controls which code snippet will execute. The if-else program is very basic and yet very important. Because it checks how well one...

19 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

How to achieve Multiple Inheritance in Java

Multiple Inheritance is the type of inheritance where one class inherits the properties of more than one super class. For example, class Child inherits (extends) the classes Father and Mother....

4 minutes read.

Selection Sort in Java

Selection Sort in Java Selection sort is also a simple sorting algorithm that works by repeatedly finding the minimum element from the unsorted portion of the input array, and placing it...

5 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.