3

I am accepting an input from user as an integer using Scanner.nextInt(). How do I verify that he enters an integer, and not an alphabetic character?

6 Answers6

2

The nextInt() method will throw an InputMismatchException if the input is not an int. So you could catch that exception and perform a conditional operation. Alternatively, checkout the hasNextInt() which will return a boolean indicating whether the next value is an int.

if (scanner.hasNextInt()) {
  int i = scanner.nextInt();
} else {
  System.out.println("Not an int");
}
orien
  • 2,130
  • 16
  • 20
1

Wrap it in a try / catch. See this post.

try {

      num = reader.nextInt();


    } catch (InputMismatchException e) {
         System.out.println("Invalid value!");
} 

Also, if you notice, in the post this is wrapped up in a loop until a valid integer is input.

Community
  • 1
  • 1
Jack
  • 9,156
  • 4
  • 50
  • 75
1

It will throw an exception if int is not entered as input. Just catch that exception and now you know the user has entered an unparsable value.

Scanner.nextInt()

Kal
  • 24,724
  • 7
  • 65
  • 65
1

If a user enters an alphabet and you expect an int, you can test for the int with Scanner.hasNextInt() and if it is false message the user.

Ulrich Palha
  • 9,411
  • 3
  • 25
  • 31
1
Scanner input = new Scanner(System.in);
int i;
System.out.print("Insert an integer number: ");

while(true)
{
    try
    {
        i = input.nextInt();
        break;
    }
    catch(InputMismatchException e)
    {
        System.out.print("You have to insert an integer number, try again: ");
    }
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

I guess you could use a try catch block if there is an Exception if it's not an int.

try {
    int aInt = new Scanner(System.in).nextInt();
}  catch (InputMismatchException e) {
    //handler-code
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
bendu
  • 391
  • 4
  • 15