do 关键字

概述

do 关键字用于创建do-while循环,与while循环不同的是,do-while循环至少执行一次循环体。

语法格式

do {
    // 循环体
} while (条件表达式);

基本用法

public class DoWhileExample {
    public static void main(String[] args) {
        // 基本do-while循环
        int count = 1;
        do {
            System.out.println("计数: " + count);
            count++;
        } while (count <= 5);

        System.out.println("循环结束,count = " + count);

        // 即使条件为false,也会执行一次
        int x = 10;
        do {
            System.out.println("x的值: " + x);
            x++;
        } while (x < 10); // 条件为false,但仍执行了一次

        System.out.println("最终x = " + x);
    }
}

do-while与while的区别

public class DoWhileVsWhile {
    public static void main(String[] args) {
        System.out.println("=== while循环 ===");
        int a = 5;
        while (a < 3) {
            System.out.println("while: a = " + a);
            a++;
        }
        System.out.println("while循环结束,a = " + a);

        System.out.println("\n=== do-while循环 ===");
        int b = 5;
        do {
            System.out.println("do-while: b = " + b);
            b++;
        } while (b < 3);
        System.out.println("do-while循环结束,b = " + b);
    }
}

实际应用示例

import java.util.Scanner;

public class DoWhileApplications {

    // 用户菜单系统
    public static void showMenu() {
        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();
    }

    // 输入验证
    public static void validateInput() {
        Scanner scanner = new Scanner(System.in);
        int number;

        do {
            System.out.print("请输入1-100之间的数字: ");
            number = scanner.nextInt();

            if (number < 1 || number > 100) {
                System.out.println("输入无效,请重新输入!");
            }
        } while (number < 1 || number > 100);

        System.out.println("您输入的有效数字是: " + number);
        scanner.close();
    }

    // 猜数字游戏
    public static void guessingGame() {
        Scanner scanner = new Scanner(System.in);
        int secretNumber = (int) (Math.random() * 100) + 1;
        int guess;
        int attempts = 0;

        System.out.println("欢迎来到猜数字游戏!");
        System.out.println("我想了一个1-100之间的数字,你能猜到吗?");

        do {
            System.out.print("请输入你的猜测: ");
            guess = scanner.nextInt();
            attempts++;

            if (guess < secretNumber) {
                System.out.println("太小了!");
            } else if (guess > secretNumber) {
                System.out.println("太大了!");
            } else {
                System.out.println("恭喜你!猜对了!");
                System.out.println("你总共猜了 " + attempts + " 次");
            }
        } while (guess != secretNumber);

        scanner.close();
    }

    public static void main(String[] args) {
        // 选择运行哪个示例
        // showMenu();
        // validateInput();
        guessingGame();
    }
}

数组和集合遍历

import java.util.*;

public class DoWhileTraversal {

    // 使用do-while遍历数组
    public static void traverseArray() {
        int[] numbers = {10, 20, 30, 40, 50};
        int index = 0;

        if (numbers.length > 0) {
            do {
                System.out.println("numbers[" + index + "] = " + numbers[index]);
                index++;
            } while (index < numbers.length);
        } else {
            System.out.println("数组为空");
        }
    }

    // 使用do-while处理列表
    public static void processList() {
        List<String> fruits = Arrays.asList("苹果", "香蕉", "橙子", "葡萄");
        Iterator<String> iterator = fruits.iterator();

        if (iterator.hasNext()) {
            do {
                String fruit = iterator.next();
                System.out.println("水果: " + fruit);
            } while (iterator.hasNext());
        }
    }

    // 批处理示例
    public static void batchProcessing() {
        Queue<String> taskQueue = new LinkedList<>();
        taskQueue.addAll(Arrays.asList("任务1", "任务2", "任务3", "任务4", "任务5"));

        int batchSize = 2;
        int processed = 0;

        while (!taskQueue.isEmpty()) {
            System.out.println("开始新的批次处理...");
            int currentBatch = 0;

            do {
                String task = taskQueue.poll();
                if (task != null) {
                    System.out.println("处理: " + task);
                    processed++;
                    currentBatch++;
                }
            } while (currentBatch < batchSize && !taskQueue.isEmpty());

            System.out.println("批次完成,处理了 " + currentBatch + " 个任务");
            System.out.println("总共已处理: " + processed + " 个任务\n");
        }
    }

    public static void main(String[] args) {
        System.out.println("=== 数组遍历 ===");
        traverseArray();

        System.out.println("\n=== 列表处理 ===");
        processList();

        System.out.println("\n=== 批处理 ===");
        batchProcessing();
    }
}

文件处理和资源管理

import java.io.*;
import java.util.Scanner;

public class DoWhileFileProcessing {

    // 逐行读取文件
    public static void readFileLineByLine(String filename) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            int lineNumber = 1;

            do {
                line = reader.readLine();
                if (line != null) {
                    System.out.println("第" + lineNumber + "行: " + line);
                    lineNumber++;
                }
            } while (line != null);

        } catch (FileNotFoundException e) {
            System.out.println("文件未找到: " + filename);
        } catch (IOException e) {
            System.out.println("读取文件时发生错误: " + e.getMessage());
        }
    }

    // 创建示例文件
    public static void createSampleFile(String filename) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(filename))) {
            writer.println("这是第一行");
            writer.println("这是第二行");
            writer.println("这是第三行");
            writer.println("这是第四行");
            writer.println("这是最后一行");
            System.out.println("示例文件创建成功: " + filename);
        } catch (IOException e) {
            System.out.println("创建文件失败: " + e.getMessage());
        }
    }

    // 处理多个文件
    public static void processMultipleFiles() {
        String[] filenames = {"file1.txt", "file2.txt", "file3.txt"};
        int index = 0;

        // 首先创建示例文件
        do {
            createSampleFile(filenames[index]);
            index++;
        } while (index < filenames.length);

        // 然后读取所有文件
        index = 0;
        do {
            System.out.println("\n=== 读取文件: " + filenames[index] + " ===");
            readFileLineByLine(filenames[index]);
            index++;
        } while (index < filenames.length);
    }

    public static void main(String[] args) {
        processMultipleFiles();
    }
}

网络和数据处理

import java.util.*;

public class DoWhileDataProcessing {

    // 数据流处理
    public static void processDataStream() {
        Queue<Integer> dataStream = new LinkedList<>();
        // 模拟数据流
        for (int i = 1; i <= 10; i++) {
            dataStream.offer(i);
        }

        List<Integer> processedData = new ArrayList<>();

        do {
            Integer data = dataStream.poll();
            if (data != null) {
                // 处理数据(这里简单地乘以2)
                int processed = data * 2;
                processedData.add(processed);
                System.out.println("处理数据: " + data + " -> " + processed);
            }
        } while (!dataStream.isEmpty());

        System.out.println("处理完成,结果: " + processedData);
    }

    // 分页数据处理
    public static void paginatedDataProcessing() {
        List<String> allData = new ArrayList<>();
        for (int i = 1; i <= 25; i++) {
            allData.add("数据项" + i);
        }

        int pageSize = 5;
        int currentPage = 0;

        do {
            int startIndex = currentPage * pageSize;
            int endIndex = Math.min(startIndex + pageSize, allData.size());

            if (startIndex < allData.size()) {
                System.out.println("处理第 " + (currentPage + 1) + " 页:");
                List<String> pageData = allData.subList(startIndex, endIndex);

                for (String item : pageData) {
                    System.out.println("  " + item);
                }

                currentPage++;
                System.out.println("页面处理完成\n");
            }
        } while (currentPage * pageSize < allData.size());

        System.out.println("所有数据处理完成,共处理 " + currentPage + " 页");
    }

    public static void main(String[] args) {
        System.out.println("=== 数据流处理 ===");
        processDataStream();

        System.out.println("\n=== 分页数据处理 ===");
        paginatedDataProcessing();
    }
}

最佳实践

public class DoWhileBestPractices {

    // 1. 确保循环体至少执行一次有意义
    public static void meaningfulExecution() {
        Scanner scanner = new Scanner(System.in);
        String input;

        // 好的做法:需要至少执行一次的输入验证
        do {
            System.out.print("请输入密码(至少6位): ");
            input = scanner.nextLine();

            if (input.length() < 6) {
                System.out.println("密码太短,请重新输入!");
            }
        } while (input.length() < 6);

        System.out.println("密码设置成功!");
        scanner.close();
    }

    // 2. 避免无限循环
    public static void avoidInfiniteLoop() {
        int maxAttempts = 3;
        int attempts = 0;
        boolean success = false;

        do {
            attempts++;
            System.out.println("尝试第 " + attempts + " 次操作");

            // 模拟操作(这里随机成功或失败)
            success = Math.random() > 0.7;

            if (success) {
                System.out.println("操作成功!");
            } else {
                System.out.println("操作失败");
            }

        } while (!success && attempts < maxAttempts);

        if (!success) {
            System.out.println("达到最大尝试次数,操作终止");
        }
    }

    // 3. 合理使用break和continue
    public static void useBreakContinue() {
        int[] numbers = {1, 2, 3, 0, 5, -1, 7, 8, 0, 10};
        int index = 0;

        do {
            if (index >= numbers.length) {
                break; // 防止数组越界
            }

            if (numbers[index] == 0) {
                System.out.println("跳过零值,索引: " + index);
                index++;
                continue; // 跳过零值
            }

            if (numbers[index] < 0) {
                System.out.println("遇到负数,终止处理");
                break; // 遇到负数时终止
            }

            System.out.println("处理数字: " + numbers[index]);
            index++;

        } while (true); // 使用break来控制退出
    }

    public static void main(String[] args) {
        System.out.println("=== 有意义的执行 ===");
        // meaningfulExecution();

        System.out.println("\n=== 避免无限循环 ===");
        avoidInfiniteLoop();

        System.out.println("\n=== 使用break和continue ===");
        useBreakContinue();
    }
}

do关键字提供了至少执行一次循环体的保证,适用于用户交互、输入验证和需要先执行后判断的场景。

powered by Gitbook© 2025 编外计划 | 最后修改: 2025-07-28 16:25:54

results matching ""

    No results matching ""