How to insist that a users input is an int?

2019-01-19 08:55发布

Basic problem here.. I will start off by asking that you please not respond with any code, as that likely will only confuse me further (programming noob). I am looking for a clear explanation on how to solve this issue that I'm having.

I have a scanner that reads input from the user. The user is prompted to enter an int value between 1 to 150 (whole numbers only). I obtain the value as follows:

    Scanner scan = new Scanner(System.in);
    int input = scan.nextInt();

And continue on with my program, and everything works fine.

Unfortunately, the code isn't exactly bulletproof, since any input that is not an integer can break it (letters, symbols, etc).

How can I make the code more robust, where it would verify that only an int was entered?

These are the results I'm hoping for:

Lets say the input was:

23 -> valid
fx -> display an error message, ask the user for input again (a while loop would do..)
7w -> error, again
3.7 -> error
$$ -> error
etc

7条回答
贼婆χ
2楼-- · 2019-01-19 09:37

Scanner.hasNextInt() returns true if the next token is a number, returns false otherwise.

In this example, I call hasNextInt(). If it returns true, I go past the while and set the input; if it returns false, then I discard the input (scanner.next();) and repeat.

Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) {
    scan.next();
}
int input = scan.nextInt();
查看更多
登录 后发表回答