Check if Input Is Integer in Java

  1. Check if Input Is Integer Using the hasNextInt Method in Java
  2. Check if the Number Is Integer Using the try...catch Block

The problem states that we need to check if the input taken in Java language is an integer.

Check if Input Is Integer Using the hasNextInt Method in Java

The System is a class that has static methods and fields. We can never instantiate the object of it. The in object is the standard input stream. This stream is already open and ready to supply input data.

The hasNextMethod is present in the Scanner class and returns true if the next token in this scanner input can get evaluated as an int value. The method throws IllegalStateException if the scanner object is closed.

package checkInputIsInt;

import java.util.Scanner;

public class CheckIntegerInput {
    public static void main(String[] args) {
        System.out.print("Enter the number: ");
        Scanner scanner= new Scanner(System.in);
        if(scanner.hasNextInt()){
            System.out.println("The number is an integer");
        }
        else{
            System.out.println("The number is not an integer");
        }
    }
}

In the first line, the input is taken from the user using console input. As the inputted text is a number, The number is an integer that gets printed.

Enter the number: 1
The number is an integer

As the inputted text is not a number, then the else condition statement gets printed.

Enter the number: Hi
The number is not an integer

Check if the Number Is Integer Using the try...catch Block

In the below code block, we use the Scanner class to take user input from the console. The Scanner class has the next method. It throws NoSuchElementException if no more tokens are available and IllegalStateException if this scanner is closed.

public class CheckIntegerInput {
    public static void main(String[] args) {
        System.out.print("Enter the number : ");
        Scanner scanner= new Scanner(System.in);
        try{
             Integer.parseInt(scanner.next());
             System.out.println("The number is an integer");
        }catch (NumberFormatException ex) {
            System.out.println("The number is not an integer ");
        }
    }

The above code will show the statement in the try block if the number is an integer. And it will execute the statement present in the catch block if the method throws an Exception from it and throws NumberFormatException if it is unable to convert a string to one of the numeric types.

The output of the above code is similar to the one in the first example code given above.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Java Integer

  • Integer Division in Java