Reputation:
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?
Upvotes: 3
Views: 4131
Reputation: 9242
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.
Upvotes: 1
Reputation: 391
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
}
Upvotes: 0
Reputation: 117597
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: ");
}
}
Upvotes: 1
Reputation: 9529
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.
Upvotes: 1
Reputation: 2200
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");
}
Upvotes: 2
Reputation: 24910
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.
Upvotes: 1