Java – How to read a valid Integer number from Console ?


This content was proof-read by Grammarly. You can Try Grammary for FREE

Problem Statement

You need to read a valid integer number from the Console in your java program. If the number is invalid , show appropriate message.

Solution

To read a valid integer from a console program , you can use the Scanner class and pass the System.in as the parameter to its constructor. The scanner class exposes a method called nextInt() which can be used to find out if the number is a valid integer or not as shown below.

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    static Scanner helper = new Scanner(System.in);
    public static void main(String[] args) {
       System.out.println("Please enter a valid integer for abundantcode.com ");
       int retValue;
       while(true)
       {
           try
           {
               retValue = helper.nextInt();
               break;
           }
           catch(InputMismatchException ex)
           {
               helper.next();
               System.out.println("This is a invalid number at abundantcode.com");
           }
       }
        System.out.println("You have entered an valid number");

    }
}

Output of the above program is

Please enter a valid integer for abundantcode.com

j

This is a invalid number at abundantcode.com

10

You have entered an valid number

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

Newsletter Signup

Subscribe to our weekly newsletter below and never miss the latest product or an exclusive offer.

%d bloggers like this: