Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤與異常

Java 多執行緒

Java 同步

Java 網路程式設計

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階 Java

Java 雜項

Java APIs & 框架

Java 類參考

Java 有用資源

Java - do...while 迴圈



Java do while 迴圈

do while 迴圈類似於 while 迴圈,區別在於 do while 迴圈至少執行一次。

do-while 迴圈是一種出口控制迴圈,其中在執行迴圈體之後檢查條件。

do while 迴圈的語法

以下是 do...while 迴圈的語法:

do {
   // Statements
}while(Boolean_expression);

do while 迴圈的執行過程

請注意,布林表示式出現在 迴圈 的末尾,因此迴圈中的語句會在測試布林表示式之前執行一次。

如果布林表示式為真,控制跳轉回 do 語句,並且迴圈中的語句再次執行。這個過程重複,直到布林表示式為假。

流程圖

下圖顯示了 Java 中 do while 迴圈的流程圖(執行過程):

Java Do While Loop

do while 迴圈示例

示例 1:使用 do while 列印範圍內的數字

在這個例子中,我們展示瞭如何使用 while 迴圈列印從 10 到 19 的數字。這裡我們初始化了一個 int 變數 x,其值為 10。然後在 do while 迴圈中,我們在 do while 迴圈體之後檢查 x 是否小於 20。在 do while 迴圈體中,我們列印 x 的值並將 x 的值加 1。while 迴圈將執行直到 x 變成 20。一旦 x 為 20,迴圈將停止執行,程式退出。

public class Test {

   public static void main(String args[]) {
      int x = 10;

      do {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      }while( x < 20 );
   }
}

輸出

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

示例 2:使用 do while 列印陣列元素

在這個例子中,我們展示瞭如何使用 do while 迴圈列印 陣列 的內容。這裡我們建立一個整數陣列 numbers 並初始化一些值。我們建立了一個名為 index 的變數來表示迭代陣列時的陣列索引。在 do while 迴圈中,我們在迴圈體之後檢查 index 是否小於陣列的大小,並使用索引表示法列印陣列的元素。在迴圈體內,index 變數加 1,迴圈繼續直到 index 變成陣列的大小,迴圈退出。

public class Test {

   public static void main(String args[]) {
      int [] numbers = {10, 20, 30, 40, 50};
      int index = 0;

      do {
         System.out.print("value of item : " + numbers[index] );
         index++;
         System.out.print("\n");
      } while( index < 5 );
   }
}

輸出

value of item : 10
value of item : 20
value of item : 30
value of item : 40
value of item : 50

Java 中的 do while 無限迴圈

無限迴圈也可以透過在 Java 中使用 do do-while 迴圈語句將“true”作為條件語句來實現。

示例:實現無限 do while 迴圈

在這個例子中,我們展示了使用 while 迴圈的無限迴圈。它將不斷列印數字,直到你按下 ctrl+c 來終止程式。

public class Test {

   public static void main(String args[]) {
      int x = 10;

      do {
         System.out.print("value of x : " + x );
         x++;
         System.out.print("\n");
      } while( true );
   }
}

輸出

value of item : 10
value of item : 20
value of item : 30
value of item : 40
value of item : 50
...
ctrl+c
java_loop_control.htm
廣告