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

如何在Java中编写循环生成并输出当月所有日期序号

解决方案

你现有代码运行后输出全是0,是因为Java中int类型数组初始化后,所有元素的默认值为0。要实现输出递增日期的需求,有两种常用实现方式:

方式一:先循环给数组赋值,再遍历输出

先通过循环给daysInMonth数组的每个元素赋值,数组下标从0开始,日期从1开始,所以每个位置的赋值逻辑为daysInMonth[i] = i + 1,赋值完成后再遍历输出即可。
完整代码如下:

public class Array {
    public static void main(String args[]) {
       int[] daysInMonth = new int[31];
       // 循环给数组赋值
       for (int i = 0; i < 31; i++) {
           daysInMonth[i] = i + 1;
       }
       // 遍历输出日期
       for (int i = 0; i < 31; i++) {
           System.out.println("Day of the month: " + daysInMonth[i]);
       }
    }
}

方式二:单循环同步完成赋值和输出

如果不需要后续单独使用赋值后的数组,可以将赋值逻辑和输出逻辑合并到同一个循环中,减少一次数组遍历:

public class Array {
    public static void main(String args[]) {
       int[] daysInMonth = new int[31];
       for (int i = 0; i < 31; i++) {
           daysInMonth[i] = i + 1;
           System.out.println("Day of the month: " + daysInMonth[i]);
       }
    }
}

内容的提问来源于stack exchange,提问作者Epicskylegend

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:27:03