理解 do-while 循环的“先执行后判断”特性
掌握其语法结构与执行流程
能够在合适场景(如菜单系统、用户输入验证)中正确使用
区分 do-while 与 while、for 循环的适用差异
避免常见语法错误(如缺少分号、条件非布尔类型)
do-while 是 Java 中唯一的出口控制循环(Exit-Controlled Loop)。与 while 和 for 不同,它先执行循环体,再检查条件,因此循环体至少会执行一次,无论条件初始是否为真。
✅ 核心特点:保证循环体最少执行 1 次
public class Main {
public static void main(String[] args) {
int c = 1;
do {
System.out.println("Hello World: " + c);
c++;
} while (c <= 5);
}
}输出结果:
Hello World: 1
Hello World: 2
Hello World: 3
Hello World: 4
Hello World: 5即使初始条件 c <= 5 为假(比如 c = 10),循环体仍会执行一次
循环在每次执行完循环体后才检查条件
想象一个游戏或工具程序,需要显示选项菜单:
1. 开始游戏
2. 查看设置
3. 退出程序
请选择操作:用户必须至少看到一次菜单,然后根据输入决定是否继续。这正是
do-while的典型用例!
Scanner sc = new Scanner(System.in);
int choice;
do {
System.out.println("1. Start Game");
System.out.println("2. Settings");
System.out.println("3. Quit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
// 处理用户选择...
} while (choice != 3);do {
// 循环体:要执行的语句
// 通常包含更新表达式(如 i++)
} while (条件表达式); // 注意:这里必须有分号!条件表达式必须返回 boolean 类型,否则编译报错
while 后必须加分号 ;,这是常见语法错误点
如果循环体只有一条语句,大括号 {} 可省略(但不推荐)
📌 示例:
while (c < 6)→ 当c小于 6 时继续循环

进入 do 块,无条件执行循环体
执行更新表达式(如 c++)
检查 while 后的条件
若为 true → 返回步骤 1
若为 false → 跳出循环
条件初始为假,仍执行一次
class Main {
public static void main(String[] args) {
int c = 0;
do {
System.out.println("Print Statement");
c++;
} while (c < 0); // 条件永远为假
}
}输出:
Print Statement✅ 证明:即使条件一开始就不成立,循环体依然执行了一次!
class Main {
public static void main(String args[]) {
int c = 1;
do {
System.out.println("Hello World");
c++;
} while (c < 6); // c 从 1 到 5,共 5 次
}
}
输出: 5 行 “Hello World”
合法但不推荐
class Main {
public static void main(String[] args) {
int c = 1;
do
System.out.println("Hello Lusifer!");
while (c >= 3); // 条件为假,只执行一次
}
}输出:
Hello Lusifer!⚠️ 警告:虽然语法合法,但强烈建议始终使用大括号,避免后续添加语句时出错。
do {
System.out.println("Hi");
} while (condition) // 编译错误!缺少分号✅ 正确写法:
} while (condition);int x = 5;
do { ... } while (x); // 编译错误!x 是 int,不是 boolean✅ 正确写法:
while (x > 0)do {
System.out.println("Stuck!");
} while (true); // 无限循环,需用 break 退出编写一个 do-while 程序,要求用户输入一个正整数,如果输入 ≤ 0 则提示错误并重新输入,直到输入有效为止。
能否用 do-while 实现斐波那契数列的前 10 项打印?尝试写出代码。
在什么情况下,do-while 比 while 更安全?举例说明(如防止空输入导致逻辑跳过)。