while 迴圈和 do-while 迴圈在 Java 中有什麼區別?


Java 中的 while 迴圈會在每次迭代的開始處測試迴圈繼續條件後執行一個或多個語句。而 do-while 迴圈則會在第一次迭代完成後測試迴圈繼續條件。因此,do-while 迴圈保證至少執行一次迴圈邏輯,而 while 迴圈卻沒有此保證。

示例

public class WhileAndDoWhileLoop {
   public static void main(String args[]) {
      int i=5;
      System.out.println("Test while Loop:");
      while(i < 5) {
         System.out.println("Iteration: "+ ++i);
      }
      System.out.println("Test do-while Loop:");
      i=5;
      do {
         System.out.println("Iteration: "+ ++i);
      } while(i < 5);
   }
}

在上面的示例中,while 迴圈語句根本不會執行。但是,do-while 迴圈會執行一次迭代。

輸出

Test while Loop:
Test do-while Loop:
Iteration: 6

更新時間: 2023-11-21

8K+ 瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.