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?
Asked
Active
Viewed 3,947 times
3

Sai Kalyan Kumar Akshinthala
- 11,704
- 8
- 43
- 67
6 Answers
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
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.

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