Skip to content

7.3 do…while 循环

do…while 循环的概念

do…while 循环是 Java 中的另一种循环结构,它与 while 循环类似,但有一个重要的区别:do…while 循环会先执行一次循环体,然后再检查条件表达式。这意味着 do…while 循环至少会执行一次循环体。

do…while 循环的语法

java
do {
    // 循环体:需要重复执行的代码
} while (条件表达式);
  • 循环体:需要重复执行的代码块
  • 条件表达式:每次循环体执行完毕后检查,返回布尔值,为 true 时继续执行循环体,为 false 时结束循环

do…while 循环的执行流程

  1. 执行循环体
  2. 检查条件表达式:
    • 如果为 true,再次执行循环体
    • 如果为 false,结束循环
  3. 重复步骤 1-2,直到条件表达式为 false

do…while 循环的使用

基本用法

java
public class DoWhileLoopExample {
    public static void main(String[] args) {
        // 打印 1 到 5
        int i = 1;
        do {
            System.out.println("i = " + i);
            i++;
        } while (i <= 5);
    }
}

输出结果:

i = 1
i = 2
i = 3
i = 4
i = 5

示例:计算 1 到 100 的和

java
public class SumExample {
    public static void main(String[] args) {
        int sum = 0;
        int i = 1;
        do {
            sum += i;
            i++;
        } while (i <= 100);
        System.out.println("Sum of 1 to 100: " + sum);
    }
}

输出结果:

Sum of 1 to 100: 5050

示例:猜数字游戏

java
import java.util.Scanner;

public class GuessNumberGame {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int secretNumber = 42;
        int guess;
        
        System.out.println("Guess a number between 1 and 100:");
        
        do {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
            
            if (guess < secretNumber) {
                System.out.println("Too low!");
            } else if (guess > secretNumber) {
                System.out.println("Too high!");
            } else {
                System.out.println("Congratulations! You guessed the number.");
            }
        } while (guess != secretNumber);
        
        scanner.close();
    }
}

示例:读取用户输入直到输入特定值

java
import java.util.Scanner;

public class ReadInputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input;
        
        System.out.println("Enter 'exit' to quit:");
        
        do {
            System.out.print("Enter something: ");
            input = scanner.nextLine();
            System.out.println("You entered: " + input);
        } while (!input.equals("exit"));
        
        System.out.println("Goodbye!");
        scanner.close();
    }
}

do…while 循环的应用场景

1. 需要至少执行一次的循环

java
// 菜单选择
int choice;
Scanner scanner = new Scanner(System.in);
do {
    System.out.println("Menu:");
    System.out.println("1. Option 1");
    System.out.println("2. Option 2");
    System.out.println("3. Exit");
    System.out.print("Enter your choice: ");
    choice = scanner.nextInt();
    
    switch (choice) {
        case 1:
            System.out.println("You chose option 1");
            break;
        case 2:
            System.out.println("You chose option 2");
            break;
        case 3:
            System.out.println("Exiting...");
            break;
        default:
            System.out.println("Invalid choice");
            break;
    }
} while (choice != 3);

2. 输入验证

java
// 输入年龄,直到输入有效
int age;
Scanner scanner = new Scanner(System.in);
do {
    System.out.print("Enter your age: ");
    age = scanner.nextInt();
    if (age < 0 || age > 120) {
        System.out.println("Invalid age. Please try again.");
    }
} while (age < 0 || age > 120);
System.out.println("Your age is: " + age);

3. 游戏循环

java
// 简单的游戏循环
boolean gameRunning = true;
do {
    // 游戏逻辑
    System.out.println("Game running...");
    
    // 检查游戏是否结束
    // gameRunning = ...;
    
    // 模拟游戏结束
    gameRunning = false;
} while (gameRunning);
System.out.println("Game over!");

示例:do…while 循环的使用

java
public class DoWhileLoopApplication {
    public static void main(String[] args) {
        // 计算一个数的阶乘
        int n = 5;
        int factorial = 1;
        int i = 1;
        do {
            factorial *= i;
            i++;
        } while (i <= n);
        System.out.println(n + "! = " + factorial);
        
        // 打印 10 以内的奇数
        System.out.println("\nOdd numbers from 1 to 10:");
        int j = 1;
        do {
            if (j % 2 != 0) {
                System.out.print(j + " ");
            }
            j++;
        } while (j <= 10);
        System.out.println();
        
        // 计算 2 的幂,直到超过 1000
        System.out.println("\nPowers of 2 until超过 1000:");
        int power = 1;
        do {
            System.out.print(power + " ");
            power *= 2;
        } while (power <= 1000);
        System.out.println();
    }
}

do…while 循环与 while 循环的比较

特性do…while 循环while 循环
执行顺序先执行循环体,再检查条件先检查条件,再执行循环体
执行次数至少执行一次可能一次也不执行
适用场景需要至少执行一次的情况条件可能一开始就不满足的情况
语法以 do 开始,while 结束以 while 开始

常见问题

1. 死循环

症状:循环永远不会结束

解决方案:确保条件表达式最终会变为 false,或在循环体中使用 break 语句

2. 循环变量未更新

症状:循环变量没有在循环体中更新,导致死循环

解决方案:确保在循环体中更新循环变量

3. 条件表达式错误

症状:循环次数不符合预期

解决方案:仔细检查条件表达式,确保它能够在适当的时候变为 false

4. 忘记加分号

症状:编译错误:error: ';' expected

解决方案:在 while 条件表达式后面添加分号

总结

do…while 循环是 Java 中的一种循环结构,它与 while 循环类似,但会先执行一次循环体,然后再检查条件表达式。这意味着 do…while 循环至少会执行一次循环体。

在使用 do…while 循环时,需要注意:

  • 条件表达式的正确设置
  • 循环变量的更新
  • 避免死循环
  • 确保在 while 条件表达式后面添加分号

通过合理使用 do…while 循环,可以处理各种需要至少执行一次的任务,提高程序的灵活性和可读性。

© 2026 编程马·菜鸟教程 版权所有