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.
Java program to validate input as integer value only
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
Java Basic Programs »