掌握while和do-while循环的语法、使用场景和最佳实践
while循环是Java中最基本的循环结构之一,它会在条件为真时重复执行代码块。while循环在循环开始前检查条件,如果条件为假,循环体可能一次都不执行。
while (条件表达式) {
// 循环体
// 要重复执行的代码
}
do {
// 循环体
// 要重复执行的代码
} while (条件表达式);
public class WhileExample {
public static void main(String[] args) {
int sum = 0;
int i = 1;
while (i <= 10) {
sum += i;
i++; // 重要:更新循环变量
}
System.out.println("1到10的和为: " + sum); // 输出: 55
}
}
import java.util.Scanner;
public class InputValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number;
// 循环直到用户输入有效数字
while (true) {
System.out.print("请输入一个1-100之间的数字: ");
number = scanner.nextInt();
if (number >= 1 && number <= 100) {
System.out.println("输入有效: " + number);
break; // 跳出循环
} else {
System.out.println("输入无效,请重新输入!");
}
}
scanner.close();
}
}
public class FindSquare {
public static void main(String[] args) {
int number = 1;
int square;
while (true) {
square = number * number;
if (square > 100) {
System.out.println("第一个大于100的平方数是: " + square);
System.out.println("对应的数字是: " + number);
break;
}
number++;
}
}
}
import java.util.Scanner;
public class MenuSystem {
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); // 用户选择0时退出
scanner.close();
}
}
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
String playAgain;
do {
int targetNumber = random.nextInt(100) + 1; // 1-100随机数
int guess;
int attempts = 0;
System.out.println("\n=== 猜数字游戏 ===");
System.out.println("我想了一个1-100之间的数字,你能猜到吗?");
do {
System.out.print("请输入你的猜测: ");
guess = scanner.nextInt();
attempts++;
if (guess < targetNumber) {
System.out.println("太小了!");
} else if (guess > targetNumber) {
System.out.println("太大了!");
} else {
System.out.println("恭喜!你猜对了!");
System.out.println("你用了 " + attempts + " 次猜测。");
}
} while (guess != targetNumber);
System.out.print("\n要再玩一次吗?(y/n): ");
playAgain = scanner.next();
} while (playAgain.equalsIgnoreCase("y"));
System.out.println("谢谢游戏,再见!");
scanner.close();
}
}
特性 | while循环 | do-while循环 |
---|---|---|
条件检查时机 | 循环开始前检查 | 循环结束后检查 |
最少执行次数 | 0次(条件为false时) | 1次(至少执行一次) |
语法结构 | while (条件) { 代码 } | do { 代码 } while (条件); |
适用场景 | 可能不需要执行的循环 | 至少需要执行一次的循环 |
常见用途 | 数据处理、条件等待 | 菜单系统、游戏循环 |
public class LoopControl {
public static void main(String[] args) {
// break示例:跳出循环
int i = 1;
while (i <= 10) {
if (i == 5) {
break; // 当i等于5时跳出循环
}
System.out.print(i + " ");
i++;
}
System.out.println("\nbreak示例结束"); // 输出: 1 2 3 4
// continue示例:跳过当前迭代
i = 1;
while (i <= 10) {
if (i % 2 == 0) {
i++;
continue; // 跳过偶数
}
System.out.print(i + " ");
i++;
}
System.out.println("\ncontinue示例结束"); // 输出: 1 3 5 7 9
}
}
// 错误示例:忘记更新循环变量
int i = 1;
while (i <= 10) {
System.out.println(i);
// 忘记写 i++; 导致无限循环
}
// 错误示例:条件永远为真
while (true) {
System.out.println("无限循环");
// 没有break语句
}
预防措施:
// 1. 清晰的循环条件
int count = 0;
while (count < maxItems) {
processItem(count);
count++; // 明确的变量更新
}
// 2. 合理的变量命名
int userChoice;
do {
userChoice = getUserInput();
processChoice(userChoice);
} while (userChoice != EXIT_OPTION);
// 3. 适当的注释
while (hasMoreData()) {
// 处理下一批数据
processNextBatch();
}
// 1. 复杂的循环条件
while (a > 0 && b < 10 && c != d && flag) {
// 条件过于复杂
}
// 2. 在循环条件中修改变量
while (++i < array.length) {
// 不推荐在条件中修改变量
}
// 3. 嵌套过深的循环
while (condition1) {
while (condition2) {
while (condition3) {
// 嵌套过深,难以理解
}
}
}