3.

Java while 文完全ガイド

編集
この記事の要点
  • while (条件) { ... }: 条件が true の間繰り返し。前判定
  • do { ... } while (条件);: 最低 1 回実行してから条件判定。後判定
  • 無限ループ: while (true) { ... break; } + 内部で break
  • break でループ脱出、continue で次の反復へ。label で多重ループ脱出も可
  • for との使い分け: 反復回数が決まっているなら for、条件次第なら while
  • Iterator を回すパターン (while (it.hasNext())) は今も健在。Stream API への置換も検討
  • 典型バグ: Off-by-one / 終了条件の更新忘れ / 浮動小数点の等価比較

while 文の基本構文

// 1. while (前判定)
int i = 0;
while (i < 5) {
    System.out.println(i);   // 0, 1, 2, 3, 4
    i++;
}

// 2. do-while (後判定: 最低 1 回実行)
int n = 10;
do {
    System.out.println(n);   // 10 (条件 false でも 1 回出る)
    n++;
} while (n < 5);

// 3. 無限ループ (条件式 true 固定 + break)
int count = 0;
while (true) {
    if (count++ >= 3) break;
    System.out.println("ping");
}

// 4. continue (次の反復へ)
for (int j = 0; j < 10; j++) {
    if (j % 2 == 0) continue;
    System.out.println(j);   // 1, 3, 5, 7, 9
}

while と do-while の違い

項目whiledo-while
条件判定タイミング前判定 (実行前)後判定 (実行後)
条件 false 時の実行回数0 回1 回
セミコロン不要末尾に ; 必須
典型用途条件次第のループ全般「最低 1 回はやる」処理 (メニュー表示など)

do-while の典型用途: メニューループ

import java.util.Scanner;

Scanner sc = new Scanner(System.in);
int choice;

do {
    System.out.println("1) 表示  2) 追加  9) 終了");
    System.out.print("選択: ");
    choice = sc.nextInt();
    switch (choice) {
        case 1 -> System.out.println("一覧表示");
        case 2 -> System.out.println("追加処理");
        case 9 -> System.out.println("終了");
        default -> System.out.println("無効");
    }
} while (choice != 9);

break と continue

// break: ループを抜ける
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
int target = 5;
int foundIdx = -1;
int i = 0;
while (i < arr.length) {
    if (arr[i] == target) {
        foundIdx = i;
        break;     // ループ脱出
    }
    i++;
}
System.out.println("見つかった index: " + foundIdx);

// continue: 次の反復へスキップ
int sum = 0;
int j = 0;
while (j < 10) {
    j++;
    if (j % 3 == 0) continue;   // 3 の倍数はスキップ
    sum += j;
}
// sum = 1+2+4+5+7+8+10 = 37

label による多重ループ脱出

ネストしたループを一気に抜けたい場合は labeled break:

outer:
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        if (i * j > 50) {
            System.out.println("脱出: i=" + i + " j=" + j);
            break outer;     // ★ outer ループまで一気に抜ける
        }
    }
}

// while にも同じく付けられる
search:
while (true) {
    for (var row : grid) {
        if (row.contains("END")) break search;
    }
}

Iterator を回す古典パターン

List list = List.of("a", "b", "c");

// while + Iterator (古典)
Iterator it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    System.out.println(s);
}

// 拡張 for 文 (Java 5+)
for (String s : list) {
    System.out.println(s);
}

// Stream API (Java 8+)
list.forEach(System.out::println);

// 削除しながら回すなら Iterator が必要 (拡張 for は ConcurrentModificationException)
List nums = new ArrayList<>(List.of(1, 2, 3, 4));
Iterator i = nums.iterator();
while (i.hasNext()) {
    if (i.next() % 2 == 0) i.remove();
}
// nums = [1, 3]

while と for の使い分け

状況推奨
反復回数が明確 (0 から n-1)for
コレクション全要素拡張 for / Stream
終了条件が状態依存while
Iterator パターンwhile + hasNext()
「最低 1 回」必要do-while
I/O 読込ループwhile ((line = reader.readLine()) != null)

I/O 読込みの定番パターン

// ファイル全行読込
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

// 標準入力 EOF まで
try (Scanner sc = new Scanner(System.in)) {
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        // ...
    }
}

典型バグと回避

// ❌ Off-by-one (1 つ多い/少ない)
int i = 0;
while (i <= arr.length) {    // <= だと ArrayIndexOutOfBoundsException
    System.out.println(arr[i]);
    i++;
}
// ✅ < にする
while (i < arr.length) { ... }

// ❌ 更新忘れ → 無限ループ
int n = 0;
while (n < 10) {
    System.out.println(n);
    // n++ 忘れ
}
// ✅ 必ず終了条件を変更する処理を入れる

// ❌ 浮動小数点の等価比較
double x = 0.0;
while (x != 1.0) {      // 0.1 を 10 回足しても 0.999999... になり永遠に止まらない
    x += 0.1;
}
// ✅ 整数で回すか EPS を使う
while (x < 1.0 - 1e-9) { x += 0.1; }

他言語との比較

言語whiledo-while 相当
Javawhile (cond) { }do { } while (cond);
C / C++同上同上
PHP同上同上
Pythonwhile cond:無し (while True: ... if not cond: break)
JavaScriptJava と同じJava と同じ
KotlinJava と同じJava と同じ
Rubywhile cond ... endbegin ... end while cond

性能

while と for は JIT 最適化後ほぼ同じ。差を気にする必要はなく、可読性で選ぶのが正解です。 Stream API はラムダ・パイプ生成のオーバーヘッドが小さくあり、超ホットループでは for/while の方が早いこともあります (が、大半のケースでは無視できる差)。

FAQ

Q: while (true) は悪い書き方?
A: そんなことはありません。ストリーム処理やイベントループの定番です。ただし必ず break 経路を確保し、終了条件のテストを書きましょう。

Q: do-while はあまり使わない?
A: 使用頻度は while より低いです。「メニュー表示」「リトライ処理」など最低 1 回実行が自然な場合のみ。

Q: 無限ループになってしまった、止め方は?
A: IDE なら停止ボタン。CLI なら Ctrl+C。原因はほぼ「終了条件を更新する処理を入れ忘れた」「条件が常に true になる式」。

編集
Post Share
子ページ

子ページはありません

同階層のページ
  1. for文
  2. 拡張for文
  3. while文
  4. do while文
  5. continue文
  6. break文