ループを終了し次のループに移る (continue文の利用) - Java

Javaでループの途中でループを終了し次のループに移る場合はcontinue文を使います。

書式

(ループ処理){
  ...(処理)
  continue;
  ...(処理)
}

コード例

package javaapplicationcontinue;
public class Main {
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    for (int i = 0; i < 2; i++) {
      for (int j = 0; j < 10; j++) {
        if (j % 2 == 0) {
          continue;
        }
        System.out.print(String.format("%d ", j));
      }
    }
    System.out.println("Loop End");
  }
}

実行結果

1 3 5 7 9 1 3 5 7 9 Loop End

参考 (ラベル付きcontinue)

continueにラベルを付けることもできます。

書式

(ラベル名):
...(ネストされたループ){
  continue (ラベル名);
}

コード例

package javaapplicationcontinue;

public class Main {
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args) {
    myloop:
    for (int i = 0; i < 2; i++) {
      for (int j = 0; j < 10; j++) {
        if (j % 2 == 0) {
          continue myloop;
        }
        System.out.print(String.format("%d ", j));
      }
    }
    System.out.println("Loop End");
  }
}

実行結果

Loop End
著者
iPentecのプログラマー、最近はAIの積極的な活用にも取り組み中。
とっても恥ずかしがり。
最終更新日: 2023-12-26
作成日: 2011-02-15
iPentec all rights reserverd.