gpt4 book ai didi

java - 与 while 循环相关的变量声明的位置

转载 作者:行者123 更新时间:2023-12-02 09:27:24 25 4
gpt4 key购买 nike

该程序提示用户输入一个整数。如果用户没有输入整数,它会再次提示,直到用户输入为止。输入整数后,它会打印“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 循环之前放置了 CorrectInput 声明,它起作用了(见下文)。但我不明白为什么我上面的内容不起作用。例如,如果我输入 3,则不会发生任何情况。如果我再次输入 3,我会得到所需的结果。

我怀疑当我输入3时, CorrectInput 被分配给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 会要求您输入 < em>另一个整数。这是因为,在 Scanner 中,hasNext 用于在使用 next 读取输入之前检查输入。

关于java - 与 while 循环相关的变量声明的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58241035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com