我创建了一个程序,使用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位。
发布于 2013-10-09 07:31:11
在这里,您已经从流中删除了一个int,所以您必须删除更多的内容。发出对sc.next()的调用:
b = sc.nextInt();
if(b < 1 || b > 100) {
System.out.print("That integer isn't between 1 and 100! Try again: ");
// sc.next(); remove this
}注意,这与前面的if -语句的情况是如何不同的:如果用户输入的东西不是一个数字,您必须通过调用next()将其从流中删除,因为否则没有其他任何东西会删除它。在这里,对nextInt的调用已经从流中删除了输入。
发布于 2013-10-09 07:22:35
您的if语句中的sc.next()是不需要的,它使您的代码跳过用户的下一个输入。下面的代码片段按照您的意愿正确工作。
private static Scanner sc;
public static void main(String[] args) throws InterruptedException {
sc = new Scanner(System.in);
int a, b;
System.out.println("Enter a number between 1 and 100: ");
while(true) {
b = 0;
if(!sc.hasNextInt()) {
System.out.println("That isn't an integer! Try again: ");
sc.next();
}
else {
b = sc.nextInt();
}
if(b < 1 || b > 100) {
System.out.println("That integer isn't between 1 and 100! Try again: ");
}
else {
a = b;
break;
}
}
System.out.println("The number is: "+a+".");
return;
}发布于 2013-10-09 07:42:59
试试下面的主板,它会起作用的
公共静态空主(String[] args)抛出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: ");
}
else{
a = b;
break;
}
}
}
System.out.print("The number is: "+a+".");}
https://stackoverflow.com/questions/19265369
复制相似问题