📅  最后修改于: 2023-12-03 14:56:57.521000             🧑  作者: Mango
在编写Java代码时,经常需要声明数组变量以存储不同类型的数据。本文将介绍如何声明并初始化一个数组变量,用于保存日历月份。
int[] months;
months = new int[12];
months[0] = 1;
months[1] = 2;
months[2] = 3;
months[3] = 4;
months[4] = 5;
months[5] = 6;
months[6] = 7;
months[7] = 8;
months[8] = 9;
months[9] = 10;
months[10] = 11;
months[11] = 12;
for (int i = 0; i < months.length; i++) {
System.out.println("Month " + (i+1) + ": " + months[i]);
}
完整代码如下:
public class Main {
public static void main(String[] args) {
int[] months;
months = new int[12];
months[0] = 1;
months[1] = 2;
months[2] = 3;
months[3] = 4;
months[4] = 5;
months[5] = 6;
months[6] = 7;
months[7] = 8;
months[8] = 9;
months[9] = 10;
months[10] = 11;
months[11] = 12;
for (int i = 0; i < months.length; i++) {
System.out.println("Month " + (i+1) + ": " + months[i]);
}
}
}
输出结果如下:
Month 1: 1
Month 2: 2
Month 3: 3
Month 4: 4
Month 5: 5
Month 6: 6
Month 7: 7
Month 8: 8
Month 9: 9
Month 10: 10
Month 11: 11
Month 12: 12
以上就是声明保存日历月的数组的Java代码实现。通过本示例,您可以掌握声明和初始化数组的方法,并学习如何访问和操作数组元素。