Java 教程

Java 控制語句

面向物件程式設計

Java 內建類

Java 檔案處理

Java 錯誤與異常

Java 多執行緒

Java 同步

Java 網路程式設計

Java 集合

Java 介面

Java 資料結構

Java 集合演算法

高階Java

Java 其他

Java APIs與框架

Java類引用

Java 有用資源

Java - continue 語句



Java continue 語句

continue語句可以用於任何迴圈控制結構。它會導致迴圈立即跳轉到迴圈的下一個迭代。

語法

continue的語法是在任何迴圈內的一個單一語句:

continue;

流程圖

Java Continue Statement

例子

示例1:在while迴圈中使用continue

在這個例子中,我們展示瞭如何使用continue語句跳過while迴圈中值為15的元素,該迴圈用於列印10到19的元素。這裡我們用值為10的int 變數 x進行了初始化。然後在while迴圈中,我們檢查x是否小於20,並在while迴圈內列印x的值並將x的值加1。while迴圈將執行直到x變為15。一旦x為15,continue語句將跳過while迴圈的執行體,迴圈繼續。

public class Test {

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

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

輸出

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

示例2:在for迴圈中使用continue

在這個例子中,我們展示瞭如何在for迴圈中使用continue語句跳過要列印的陣列的元素。這裡我們建立一個整數陣列numbers並初始化一些值。我們在for迴圈中建立了一個名為index的變數來表示陣列的索引,檢查它是否小於陣列的大小並將其加1。在for迴圈體中,我們使用索引表示法列印陣列的元素。一旦遇到值為30,continue語句就會跳轉到for迴圈的更新部分,迴圈繼續。

public class Test {

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

      for(int index = 0; index < numbers.length; index++) {
         if(numbers[index] == 30){
            continue;
         }
         System.out.print("value of item : " + numbers[index] );         
         System.out.print("\n");
      }
   }
}

輸出

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

示例3:在do while迴圈中使用continue

在這個例子中,我們展示瞭如何使用continue語句跳過do while迴圈中值為15的元素,該迴圈用於列印10到19的元素。這裡我們用值為10的int變數x進行了初始化。然後在do while迴圈中,我們在迴圈體之後檢查x是否小於20,並在while迴圈內列印x的值並將x的值加1。while迴圈將執行直到x變為15。一旦x為15,continue語句將跳過while迴圈的執行體,迴圈繼續。

public class Test {

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

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

輸出

value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 16
value of x : 17
value of x : 18
value of x : 19
value of x : 20
java_loop_control.htm
廣告