第16章

Java while循环

掌握while和do-while循环的语法、使用场景和最佳实践

学习目标

while循环详解

while循环是Java中最基本的循环结构之一,它会在条件为真时重复执行代码块。while循环在循环开始前检查条件,如果条件为假,循环体可能一次都不执行。

while循环

语法结构:
while (条件表达式) {
    // 循环体
    // 要重复执行的代码
}
  • 先判断条件,再执行循环体
  • 条件为false时不执行循环体
  • 适合不确定循环次数的情况
  • 需要注意避免无限循环

do-while循环

语法结构:
do {
    // 循环体
    // 要重复执行的代码
} while (条件表达式);
  • 先执行循环体,再判断条件
  • 至少执行一次循环体
  • 适合需要至少执行一次的场景
  • 注意分号不能省略

while循环实战示例

基础while循环

示例1:计算1到10的和
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
    }
}

用户输入处理

示例2:输入验证
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();
    }
}

查找和计算

示例3:查找第一个大于100的平方数
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++;
        }
    }
}

do-while循环实战示例

菜单系统

示例1:简单菜单系统
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();
    }
}

游戏循环

示例2:猜数字游戏
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 vs do-while 对比

特性 while循环 do-while循环
条件检查时机 循环开始前检查 循环结束后检查
最少执行次数 0次(条件为false时) 1次(至少执行一次)
语法结构 while (条件) { 代码 } do { 代码 } while (条件);
适用场景 可能不需要执行的循环 至少需要执行一次的循环
常见用途 数据处理、条件等待 菜单系统、游戏循环
选择建议:
  • 当循环体可能一次都不执行时,使用while循环
  • 当循环体至少需要执行一次时,使用do-while循环
  • 菜单系统、用户交互通常使用do-while循环
  • 数据处理、文件读取通常使用while循环

循环控制和优化

循环控制语句

break和continue的使用
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语句
}

预防措施:

  • 确保循环变量在每次迭代中都有变化
  • 检查循环条件是否能够变为false
  • 在无限循环中提供退出条件
  • 使用调试工具监控循环执行

while循环最佳实践

推荐做法

// 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) {
            // 嵌套过深,难以理解
        }
    }
}
  • 避免过于复杂的循环条件
  • 不在条件表达式中修改变量
  • 避免过深的循环嵌套
  • 不要忽略循环变量的更新

实战练习

💻 查看完整代码 - 在线IDE体验
练习建议:
  1. 基础练习:编写程序计算阶乘、斐波那契数列
  2. 应用练习:实现简单的计算器、密码验证系统
  3. 综合练习:开发小游戏、数据处理程序
  4. 优化练习:改进循环性能、减少时间复杂度

章节总结