变量声明相对于 while 循环的位置



此程序提示用户输入整数。如果用户未输入整数,它将再次提示,直到他们输入整数。输入整数后,它将打印"CS115"五次。

public static void main(String[] args) {
String CS115 = "Hello CS115";
Scanner scan = new Scanner ( System.in );
System.out.print("Enter an integer: ");
int correctInput = scan.nextInt();
while(!scan.hasNextInt()) {
System.out.println("Try again > "); 
scan.next();
}

for (int i = 1; i <= correctInput; i++)  {
System.out.println(CS115);
}
}

一时兴起,我将正确的输入声明放在 while 循环之后和 for 循环之前,它起作用了(见下文(。但我不明白为什么我上面的东西不起作用。例如,如果我输入 3,则没有任何反应。如果我再次输入 3,我会得到想要的结果。

我怀疑当我输入 3 时,正确输入被分配给 3,而 while 循环被忽略。我相信这部分我理解。但是为什么 for 循环不能使用此正确的输入值执行呢?程序只是终止,直到我第二次输入值。在第二个条目中,将运行 for 循环。这是怎么回事?

public static void main(String[] args) {
String CS115 = "Hello CS115"
Scanner scan = new Scanner ( System.in );
System.out.print("Enter an integer: ");
while(!scan.hasNextInt()) {
System.out.println("Try again > "); 
scan.next();
}
int correctInput = scan.nextInt();
for (int i = 1; i <= correctInput; i++)  {
System.out.println(CS115);
}           
}

您应该首先调用hasNextInt以检查用户是否键入了整数,然后调用nextInt以读取该整数。如果在hasNextInt之前调用nextIntnextInt将读取一个整数,但随后hasNextInt会期望您键入另一个整数。 这是因为,在Scanner中,hasNext用于在用next读取输入之前检查输入。

最新更新