タイトル: do while文
SEOタイトル: Java do-while文 完全ガイド|while との違い・最低1回実行・無限ループ・break / continue
| この記事の要点 |
|
do-while 文とは
do-while 文は Java の後判定型繰り返し制御構文です。「先に処理を 1 回実行してから条件を評価し、条件が真である間ループを継続する」動きをします。
必ず 1 回は本体が実行されるため、「ユーザーに入力を求める」「ファイルを少なくとも 1 回読む」のような初回実行が前提のケースに向きます。
構文
do {
// 繰り返し実行する処理
} while (条件式); // <- 末尾セミコロン必須
実装例
int val = 0;
do {
System.out.println("val = " + ++val);
} while (val < 10);
出力結果
val = 1
val = 2
val = 3
val = 4
val = 5
val = 6
val = 7
val = 8
val = 9
val = 10
while 文との違い
| 項目 | while 文 | do-while 文 |
|---|---|---|
| 条件評価のタイミング | 本体実行前 | 本体実行後 |
| 本体の最低実行回数 | 0 回 | 1 回 |
| 典型用途 | 条件成立中の繰り返し | 最低 1 回必要な繰り返し |
| セミコロンの位置 | 不要 | while ( ); の末尾 |
実行回数の違い(条件が初回から false の場合)
int x = 100;
// while: 0 回実行
while (x < 10) {
System.out.println("while");
}
// do-while: 1 回実行される
do {
System.out.println("do-while");
} while (x < 10);
// 出力: do-while
典型ユースケース
1. ユーザー入力の検証
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int age;
do {
System.out.print("年齢を入力 (0-120): ");
age = sc.nextInt();
} while (age < 0 || age > 120);
System.out.println("入力された年齢: " + age);
2. メニュー表示・選択
int choice;
do {
System.out.println("1: 新規登録");
System.out.println("2: 一覧表示");
System.out.println("9: 終了");
System.out.print("選択: ");
choice = sc.nextInt();
switch (choice) {
case 1: register(); break;
case 2: list(); break;
case 9: break;
default: System.out.println("不正な入力");
}
} while (choice != 9);
3. リトライ処理
int retry = 0;
boolean success;
do {
success = callExternalApi();
retry++;
} while (!success && retry < 3);
break と continue
break: ループを抜ける
int i = 0;
do {
if (i == 5) break;
System.out.println(i);
i++;
} while (i < 10);
// 0 1 2 3 4
continue: 次回繰り返しへ
int i = 0;
do {
i++;
if (i % 2 == 0) continue; // 偶数はスキップ
System.out.println(i);
} while (i < 10);
// 1 3 5 7 9
無限ループ
do {
String line = reader.readLine();
if (line == null) break;
process(line);
} while (true);
注意点
- 末尾のセミコロンを忘れるとコンパイルエラー
- ループ内で条件変数を更新しないと無限ループになる
- 「1 回も実行したくない」ケースでは
whileを使う - 後判定の利点と引き換えに、条件が見えづらい(末尾を見るまで分からない)コードになりがち。複雑になるなら
while+ 初回フラグの方が読みやすい場合もある
do-while のフローチャート
┌──────────────────────┐
│ ループ本体を実行 (1回目) │
└──────────┬───────────┘
│
┌─────▼─────┐
│ 条件式評価 │
└─────┬─────┘
│
true │ false
│
┌──────────▼─────────┐
│ 本体を再度実行 │
└──────────┬─────────┘
│
繰り返し ────────► ループ終了
他言語との比較
| 言語 | 後判定ループ構文 |
|---|---|
| Java / C / C++ / C# | do { ... } while (cond); |
| JavaScript / TypeScript | do { ... } while (cond); |
| PHP | do { ... } while ($cond); |
| Kotlin | do { ... } while (cond) |
| Python | 存在しない。while True: ... if not cond: break で代用 |
| Go | 存在しない。for で代用 |
| Ruby | begin ... end while cond(非推奨化) |
ラベル付き break / continue
Java では多重ループから一気に抜けたいとき、ラベル付き break が便利です。do-while でも使えます。
outer:
do {
for (int i = 0; i < 10; i++) {
if (cond(i)) {
break outer; // do-while 自体を抜ける
}
}
} while (canRetry());