HOW DO WE CHECK FOR AN INTEGER USER INPUT IN JAVA

Steven Hill

Total Post:10

Points:72
Posted by  Steven Hill
 661  View(s)
Ratings:
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();





  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How do we check for an integer user input in java

    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 {
     
    Integer.parseInt(input);
    } catch (Exception e) {
       return false;
            }
         return true;
    }



Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!