如何坚持用户输入是一个int? [英] How to insist that a users input is an int?

查看:86
本文介绍了如何坚持用户输入是一个int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的基本问题..我首先要求你不要回复任何代码,因为这可能只会让我更加困惑(编程菜鸟)。我正在寻找一个关于如何解决这个问题的明确解释。

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.

我有一个扫描仪可以读取用户的输入。提示用户输入1到150之间的int值(仅限整数)。我获得如下值:

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

如何使代码更加健壮,哪里可以验证只输入了一个int?

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

这些是我希望的结果:

让我们说输入是:

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


推荐答案

Scanner.hasNextInt()返回 true 如果下一个标记是数字,则返回 false 否则。

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

在这个例子中,我调用hasNextInt()。如果它返回 true ,我会经过一段时间并设置输入;如果它返回 false ,那么我丢弃输入( scanner.next(); )并重复。

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

这篇关于如何坚持用户输入是一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆