You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何用三种循环实现一周7天字符串数组的初始化与打印

Java三种循环实现数组初始化与打印

以下是完全符合需求的可运行代码,分别用while、do-while、for三种循环完成数组初始化和内容打印:

public class MyClass {
    public static void main(String args[]) {
        // 声明存储一周7天的数组变量
        String[] days;
        // 提前定义星期常量作为赋值数据源,也可在循环内直接根据下标赋值
        String[] weekValues = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

        // ------------------------------
        // 1. while循环实现
        // ------------------------------
        days = new String[7];
        int index = 0;
        // 数组初始化
        while (index < days.length) {
            days[index] = weekValues[index];
            index++;
        }
        // 打印内容
        System.out.println("===== while循环输出 =====");
        index = 0;
        while (index < days.length) {
            System.out.println(days[index]);
            index++;
        }

        // ------------------------------
        // 2. do-while循环实现
        // ------------------------------
        days = new String[7];
        index = 0;
        // 数组初始化
        do {
            days[index] = weekValues[index];
            index++;
        } while (index < days.length);
        // 打印内容
        System.out.println("\n===== do-while循环输出 =====");
        index = 0;
        do {
            System.out.println(days[index]);
            index++;
        } while (index < days.length);

        // ------------------------------
        // 3. for循环实现
        // ------------------------------
        days = new String[7];
        // 数组初始化
        for (int i = 0; i < days.length; i++) {
            days[i] = weekValues[i];
        }
        // 打印内容
        System.out.println("\n===== for循环输出 =====");
        for (int i = 0; i < days.length; i++) {
            System.out.println(days[i]);
        }
    }
}

注意事项

  • 每次切换循环实现前都会重新创建空的days数组,保证每种循环都独立完成初始化操作,符合需求要求
  • do-while循环会先执行一次循环体再判断终止条件,本需求中数组长度固定为7,不会出现下标越界问题,如果是动态长度的数组要额外判断空值和长度
  • 如果不想提前定义weekValues常量数组,可以在循环内通过下标判断赋值,示例:
// for循环内直接赋值示例
for (int i = 0; i < days.length; i++) {
    switch (i) {
        case 0: days[i] = "Monday"; break;
        case 1: days[i] = "Tuesday"; break;
        // 剩余case自行补全即可
    }
}

内容的提问来源于stack exchange,提问作者Freddie Montilla Jr.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 17:15:02