我用掃描儀把從用戶編號和保存創建的程序爲「一」時,它是從1到100的整數請參閱下的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位。
啊,所以我把b中的整數從流中移除了呢?完美的答案,非常感謝! – DanielDC88