While循环内的Java IF语句无法正常运行

bf1o4zei  于 2022-10-01  发布在  Java
关注(0)|答案(2)|浏览(118)

我在我创建的一些Java代码中遇到了问题,我正在尝试创建一个包含在While循环中的if语句,以便它在不同的打印命令之间无限期地运行,同时基于一个变量,该变量在每次循环时都会增加。代码应该将时间变量设置为0,然后进入While循环。在While循环中,它应该始终做的第一件事是用++将时间变量加1,然后输入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.");
      }
    }
  }
}
xurqigkl

xurqigkl1#

如果您的If语句不涵盖时间介于0和5之间的情况。因此,当“time”从这些值开始时,将命中带有错误消息的Else语句

nr9pn0ug

nr9pn0ug2#

Your code is never able to reach the 12, 19, and 24 conditions. If the time is say 13, the if statement will first check if the time is greater than 5, which 13 is. So it will enter the first block and print "Good Morning".

To fix this you could change the order that you are checking the time, so that the largest checks come first and if not will fall through to the smaller checks. Try something like this:

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.");
      }
    }
  }
}

相关问题