簡體   English   中英

Java while 循環中的 if 語句無法正常運行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM