首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java do-while 迴圈完整教學:語法特性、執行流程與三大迴圈對比實戰

     編輯:Java 相關知識

前言

do-while 是 Java 三大迴圈結構之一,核心特徵是先執行迴圈體,再判斷條件,保證至少執行一次。這特性適用於選單驅動程式、輸入驗證、至少一次業務邏輯等場景。本文系統性解析語法、流程、陷阱與 while/for 對比。

語法結構

do {
    // 迴圈體 (至少執行一次)
    statement(s);
} while (boolean_expression); // 注意結尾分號!

執行流程圖解

      ┌─────────────┐
      │  進入 do    │
      └──────┬──────┘
             ▼
      ┌─────────────┐
      │ 執行迴圈體  │ ← 無條件執行第一次
      └──────┬──────┘
             ▼
      ┌─────────────┐
      │ 條件判斷    │ ← true 回迴圈體,false 跳出
      │ (boolean)   │
      └──────┬──────┘
        ┌────┴────┐
       true      false
        │         │
        ▼         ▼
   ┌─────────┐  結束迴圈
   │ 繼續執行 │
   └────┬────┘
        │
        └──────────┘ (回到條件判斷)

經典範例:1 到 100 求和

public class DoWhileSum {
    public static void main(String[] args) {
        int i = 1;
        int sum = 0;
        
        do {
            sum += i;
            i++;
        } while (i <= 100);
        
        System.out.println("1+2+...+100 = " + sum); // 5050
    }
}

關鍵特性驗證:至少執行一次

public class DoWhileAtLeastOnce {
    public static void main(String[] args) {
        int j = 5; // 初始值已不符合條件 j < 3
        
        do {
            System.out.println("執行了!j = " + j); // 仍會執行一次
            j++;
        } while (j < 3);
        
        // 輸出:執行了!j = 5
    }
}

對比:while (j < 3) 條件前置,零次執行;do-while 條件後置,一次執行。

實戰場景:選單驅動程式

import java.util.Scanner;

public class MenuDrivenApp {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int choice;
        
        do {
            System.out.println("\n=== 學生管理系統 ===");
            System.out.println("1. 新增學生");
            System.out.println("2. 查詢學生");
            System.out.println("3. 刪除學生");
            System.out.println("0. 離開系統");
            System.out.print("請選擇: ");
            
            choice = scanner.nextInt();
            
            switch (choice) {
                case 1: System.out.println("→ 執行新增邏輯"); break;
                case 2: System.out.println("→ 執行查詢邏輯"); break;
                case 3: System.out.println("→ 執行刪除邏輯"); break;
                case 0: System.out.println("→ 感謝使用,再見!"); break;
                default: System.out.println("→ 選項無效,請重新輸入");
            }
        } while (choice != 0);
        
        scanner.close();
    }
}

實戰場景:輸入驗證 (強制合法輸入)

import java.util.Scanner;

public class InputValidation {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age;
        
        do {
            System.out.print("請輸入年齡 (1-120): ");
            while (!scanner.hasNextInt()) {
                System.out.print("格式錯誤,請輸入數字: ");
                scanner.next(); // 清除無效輸入
            }
            age = scanner.nextInt();
            
            if (age < 1 || age > 120) {
                System.out.println("範圍錯誤!");
            }
        } while (age < 1 || age > 120);
        
        System.out.println("錄入成功:年齡 = " + age);
        scanner.close();
    }
}

三大迴圈深度對比

特性whiledo-whilefor
條件檢查時機前置 (Pre-test)後置 (Post-test)前置 (Pre-test)
最少執行次數010
適用場景未知次數、條件複雜選單、輸入驗證、至少一次已知次數、計數器控制
變數作用域外部宣告外部宣告可在初始化區宣告 (區域)
語法靈活度高中高 (增強 for、多計數器)
break/continue支援支援支援

進階用法與陷阱

1. 巢狀 do-while

int i = 1;
do {
    int j = 1;
    do {
        System.out.print("*");
        j++;
    } while (j <= 5);
    System.out.println();
    i++;
} while (i <= 3);

2. 搭配 break/continue

int x = 0;
do {
    x++;
    if (x == 3) continue; // 跳過本次剩餘,直接判斷條件
    if (x == 7) break;    // 直接跳出迴圈
    System.out.println(x);
} while (x < 10);

3. 常見錯誤:忘記分號

// ❌ 編譯錯誤
do {
    System.out.println("test");
} while (true)  // 缺少分號

// ✅ 正確
do {
    System.out.println("test");
} while (true);

4. 無限迴圈寫法

do {
    // 業務邏輯
    if (exitCondition) break;
} while (true); // 或 while (1 == 1)

效能微觀差異

  • 現代 JIT 編譯器會優化熱點迴圈,三種迴圈機器碼層面幾乎無差異
  • for 迴圈變數作用域最小,有利於暫存器分配與逃逸分析
  • 選擇迴圈類型應優先考慮語意清晰度,而非微觀效能

總結:如何選擇迴圈?

  1. 明確次數 / 計數器控制 → for (含增強 for)
  2. 未知次數、條件複雜、可能零次 → while
  3. 至少執行一次、選單驅動、輸入驗證 → do-while

掌握三大迴圈的語意差異與適用邊界,能寫出更符合業務邏輯、更易維護的程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved