[英]Java if statement within while loop not functioning properly
我在创建一些 java 代码时遇到问题,我试图创建一个包含在 while 循环中的 if 语句,以便它在基于每次增加的变量的不同打印命令之间旋转时无限期运行通过循环。 代码应该是将时间变量设置为 0,然后进入 while 循环。 在 while 循环中,它应该始终做的第一件事是使用 ++ 将时间变量增加一个,然后输入 if 语句并打印三种不同的可能打印命令之一,然后当时间变量大于 24 时设置时间到 0,因此循环回到第一个可能的打印命令。 我仍在学习 java 并且非常糟糕,所以如果这个问题很愚蠢,我深表歉意。
代码:
class Main {
public static void main(String[] args) {
int time = 0;
while (true) {
time++;
if (time > 5) {
System.out.println("Good morning.");
} else if (time > 12) {
System.out.println("Good afternoon.");
} else if (time > 19) {
System.out.println("Good night.");
} else if (time > 24) {
time = 0;
} else {
System.out.println("If this message is printed, the code is not working properly.");
}
}
}
}
当时间在 0 到 5 之间时,您的 if 语句不包括这种情况。因此,当“时间”从这些值开始时,您的 else 语句将被命中
您的代码永远无法达到 12、19 和 24 条件。 如果时间是 13,if 语句将首先检查时间是否大于 5,即 13。 所以它会进入第一个块并打印“Good Morning”。
要解决此问题,您可以更改检查时间的顺序,以便最大的支票排在第一位,如果不是,则将落到较小的支票上。 尝试这样的事情:
class Main {
public static void main(String[] args) {
int time = 0;
while (true) {
time++;
if (time > 24) {
time = 0;
}else if (time > 19) {
System.out.println("Good night.");
} else if (time > 12) {
System.out.println("Good afternoon.");
} else if (time > 5) {
System.out.println("Good morning.");
} else {
System.out.println("If this message is printed, the code is not working properly.");
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.