当前位置: 动力学知识库 > 问答 > 编程问答 >

How can I verify that a user enters an integer or alphabetic character in Java?

问题描述:

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?

网友答案:

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");
}
网友答案:

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()

网友答案:

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.

网友答案:
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: ");
    }
}
网友答案:

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.

网友答案:

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
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: