如何在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
相关产品推荐
相关产品推荐

