1

In my program I want an integer input by the user. I want an error message to be show when user inputs a value which is not an integer. And How can I do this in loop. i am just a beginner please help me.

        //code that i already try
        Scanner input = new Scanner(System.in);
        int age;
        String AGE ;


        System.out.print("\nEnter Age       : "); 
        AGE = input.nextLine();
        try{
          age = Integer.parseInt(AGE);

        }catch (NumberFormatException ex){

             System.out.print("Invalid input " + AGE + " is not a number");
        }

4 Answers4

1

You use an while loop and break on sucess

int age;

while (true) {   // wil break on sucess 
   Scanner input = new Scanner(System.in);
   System.out.print("\nEnter Age       : "); 
   String AGE = input.nextLine();
    try{
      age = Integer.parseInt(AGE);
      break;  
    }catch (NumberFormatException ex){
        System.out.print("Invalid input " + AGE + " is not a number");
    }
}
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

This is the better way to check user input is integer or Not -

public static void onlyInteger() {


    int myInt = 0;
    System.out.println(" Please enter Integer");
    do {
        while (!input.hasNextInt()){
            System.out.println(" Please enter valid Integer :");
            input.next();
        }
        myInt = input.nextInt();
    }while (myInt  <= 0);

}

Hope this will help.

Dipankar Baghel
  • 1,932
  • 2
  • 12
  • 24
0

If you are trying to capture the age input as an integer, you would not need the integer array as such

'int age [] = new int [100];'

You can use Scanner's nextInt() method to capture integer input.

This will throw InputMismatchException exception in case the input is not an integer.Try below code.

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter Age: ");
        try {
            int number = input.nextInt();
            System.out.println("Age entered " + number);
        } catch (InputMismatchException e) {
            System.out.println("Incorrect Input for Age.Please enter integer Integer value");
        }
    }
0

To check the input is an integer or any number :

Step 1 is to Read the input as Java Object, then
Object o = new Integer(33);// or can be new Float(33.33)...

if(o instanceof Number) {
   System.out.println(o +" is number");// do your thing here
}

The abstract class Number is the superclass of platform classes representing numeric values that are convertible to the primitive types byte, double, float, int, long, and short.

JavaDoc Number

Ismail
  • 1,188
  • 13
  • 31