如何使用Scanner仅接受有效的int作为输入 [英] How to use Scanner to accept only valid int as input
问题描述
我正在尝试使一个小程序更强大,我需要一些帮助。
I'm trying to make a small program more robust and I need some help with that.
Scanner kb = new Scanner(System.in);
int num1;
int num2 = 0;
System.out.print("Enter number 1: ");
num1 = kb.nextInt();
while(num2 < num1) {
System.out.print("Enter number 2: ");
num2 = kb.nextInt();
}
-
2号必须更大比数字
Number 2 has to be greater than number 1
此外,如果用户输入字符而不是数字,我希望程序自动检查并忽略。因为现在当用户输入例如 r
而不是数字时,程序就会退出。
Also I want the program to automatically check and ignore if the user enters a character instead of a number. Because right now when a user enters for example r
instead of a number the program just exits.
推荐答案
使用 Scanner.hasNextInt()
:
如果此扫描器输入中的下一个标记可以解释为 int
true >使用 nextInt()
方法在默认基数中的值。扫描仪不会超过任何输入。
Returns
true
if the next token in this scanner's input can be interpreted as anint
value in the default radix using thenextInt()
method. The scanner does not advance past any input.
这里有一个片段来说明:
Here's a snippet to illustrate:
Scanner sc = new Scanner(System.in);
System.out.print("Enter number 1: ");
while (!sc.hasNextInt()) sc.next();
int num1 = sc.nextInt();
int num2;
System.out.print("Enter number 2: ");
do {
while (!sc.hasNextInt()) sc.next();
num2 = sc.nextInt();
} while (num2 < num1);
System.out.println(num1 + " " + num2);
您没有 parseInt
或担心 NumberFormatException
。请注意,由于 hasNextXXX
方法不会超过任何输入,您可能必须调用 next()
如果您想要跳过垃圾,如上所示。
You don't have to parseInt
or worry about NumberFormatException
. Note that since the hasNextXXX
methods don't advance past any input, you may have to call next()
if you want to skip past the "garbage", as shown above.
- How do I keep a scanner from throwing exceptions when the wrong type is entered? (java)
这篇关于如何使用Scanner仅接受有效的int作为输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!