问题描述
我正在努力让一个小程序更健壮,我需要一些帮助.
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 必须大于数字 1
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.
推荐答案
返回 true
如果此扫描器输入中的下一个标记可以使用 nextInt()
解释为默认基数中的 int
值方法.扫描仪不会通过任何输入.
这里有一个片段来说明:
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.
这篇关于如何使用 Scanner 只接受有效的 int 作为输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!