import java.util.Scanner;
import static java.lang.System.out;
public class TestingStuf2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a number");
int number = keyboard.nextInt();
while (number < 10) {
if (number < 10) {
out.println("This number is too small.");
keyboard.nextInt();
}else{
out.println("This number is big enough.");
}
}
keyboard.close();
}
}
我只是在循环这段代码时遇到了一些麻烦。我刚刚开始学习 Java,这些循环一直让我感到困惑。当我运行这个程序时,如果我输入一个小于 10 的数字,我会收到一条消息“这个数字太小”,然后它允许我再次输入。但是,如果我输入一个大于 10 的数字,我会得到同样的消息。此外,如果我输入的第一个数字大于 10,我根本没有收到任何消息,程序就结束了。为什么会发生这种情况?
最佳答案
我认为您忘记重新分配 number
多变的。这就是原因
However if I then type a number greater than 10 I get the same message.
请尝试下面的代码。感谢@Dev.Joel 的评论。我已将循环修改为 do-while
以便更好地适应实际情况。
import java.util.Scanner;
import static java.lang.System.out;
public class TestingStuf2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a number");
int number = keyboard.nextInt();
do{
if (number < 10) {
out.println("This number is too small.");
/*
* You should reassign number here
*/
number = keyboard.nextInt();
}else{
out.println("This number is big enough.");
}
}while(number < 10);
keyboard.close();
}
}
我建议您使用break point
调试你的问题。例如,在您的情况下,您将 2 分配给 number
,并打印“此数字太小”。接下来,您使用 keyboard.nextInt()
让用户输入另一个 int。然而,数字仍然是2。因此条件number < 10
无论这次输入什么都是 true,并且 "This number is too small"
再次打印。
关于java - 如何让循环在我的 Java 程序中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39239552/