我创建了一个程序,使用 Scanner 从用户那里获取一个数字,并在它是 1 到 100 的整数时将其保存到“a”。请参阅下面的 Java 文件:
public class Parity_Check {
private static Scanner sc;
public static void main(String[] args) throws InterruptedException {
sc = new Scanner(System.in);
int a, b;
System.out.print("Enter a number between 1 and 100: ");
while(true) {
b = 0;
if(!sc.hasNextInt()) {
System.out.print("That isn't an integer! Try again: ");
sc.next();
}
else{
b = sc.nextInt();
if(b < 1 || b > 100) {
System.out.print("That integer isn't between 1 and 100! Try again: ");
sc.next();
}
else{
a = b;
break;
}
}
}
System.out.print("The number is: "+a+".");
}
}
我遇到的问题如下:程序返回“那个整数不在 1 到 100 之间!再试一次:,“它等待来自用户的两个输入(而不是它应该输入的那个)——第一个被完全忽略!这是我为说明问题而运行的控制台会话:
"Enter a number between 1 and 100: 2.5
That isn't an integer! Try again: 101
That integer isn't between 1 and 100! Try again: Apple.
42
The number is: 42.”
正如你所看到的,它甚至没有注意到输入"Apple".
我完全迷失了为什么这不能正常工作,就像这样:
"Enter a number between 1 and 100: 2.5
That isn't an integer! Try again: 101
That integer isn't between 1 and 100! Try again: Apple.
That isn't an integer! Try again: 42
The number is: 42.”
我对Java很陌生,所以一个很好解释的答案将是天赐之物;我对它为什么不起作用比如何修复它更感兴趣,因为希望我能够学习。
顺便说一句,我正在使用最新版本的 Eclipse 64 位。