ADVERTISEMENT
ADVERTISEMENT

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

Java Basic Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.