Home > DeveloperSection > Forums > How do we check for an integer user input in java
Steven Hill
Steven Hill

Total Post:10

Posted on    October-07-2015 7:10 AM

 Java Exception Handling  Java 

 1 Reply(s)
 326  View(s)
Rate this:
Hi Everyone, i am working on  a java application, in which i took  integer input from the user. If the user enter an integer than it is working fine, but in case he inputs a digit or any decimal number , the application throws an exception. So i want to implement a validation for user input, so that only integer values will be accepted. I need a way to check whether the input values is integer type or not, here is a part of my code :

//Taking input through scanner
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number ");
int input = sc.nextInt();

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    October-07-2015 8:01 AM

Hi Steve,

This is a very commonly used issue of validation. I think you don't need to directly check  whether the input is integer or not. So, don't take input as integer, take this as string using Scanner.next() method. Now you change this to integer if it changed successfully that means it a valid integer input. Create a method which would return a boolean based on your input. Follow the below code :

//Taking input through scanner
Scanner sc = new Scanner (System.in);
System.out.println("Enter the number ");
//int input = sc.nextInt(); 

int input = sc.next(); // First take the input as String
valdiateInput(input); // Now validate it by passing the string value in the boolean method, if it retuns true it is a valid integer, else it's not

//Try to convert the input into integer, if its an integer the line will be executed and the method returns true, if it's not it will throw exception which handled in catch block  and the method will return false
boolean validateInput(String input) {
     try {
} catch (Exception e) {
   return false;
     return true;

Don't want to miss updates? Please click the below button!

Follow MindStick