Home » Java programs » Java basic programs

Java program to validate input as integer value only



In this java program, we are going to learn how to validate user input? Here, we are reading an integer value, if someone’s input is not an integer it will through an error and reads the value again.
Submitted by IncludeHelp, on November 25, 2017

Here, we have to create a java program, in which we can read only integer values. If someone input any value except integer it will give an error and ask to input value again.

Program

import java.util.Scanner;
import java.util.InputMismatchException;
public class Scan
{   
	// create function readint for reading input value.
	public static int readInt(String msg)
	{ 
		boolean error=false;
		int x=0;
		do
		{
			try
			{
				// create object of scanner class.
				Scanner KB=new Scanner(System.in);

				// enter here.
				System.out.print("Enter integer : ");
				x=KB.nextInt();
				error=false;
			}
			catch(InputMismatchException e)
			{
				// accept integer only.
				System.out.println("Invalid Input..Pls Input Integer Only..");
				error=true;
			}
		}
		while(error);
		return(x);
	}
}

Output

Enter integer : Good
Invalid Input..Pls Input Integer Only..
Enter integer : 10
Enter integer : 10





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.