如何初始化一个二维数组?

我在初始化数组时遇到问题。当我尝试绘制数组时,我得到了一个NullPointerException.


我需要访问我从另一个类声明数组的类,这就是为什么它是static.


这是我的代码:


static int[][] DayOfTheMonth = new int[3][10];



public static void ArrayValue() {

    for (int column = 0; DayOfTheMonth.length < 4; column++) {

        for (int row = 10; DayOfTheMonth[column].length < 10; row++) {

            if (DaysofTheMonth <= Tag.MaximumDaysOfAMonth()) {


                DayOfTheMonth.[column][row] = Date.getDate() + DaysofTheMonth;

                DaysofTheMonth++;


            } else if (DaysofTheMonth > Tag.MaxDay()) {

                DaysofTheMonth = 1;


                if (Month != 12)

                    Month++;

                else {

                    Month = 0;

                    Year++;


                }

            }

        }

    }

}

另一个问题是,当我尝试通过我的主类访问该方法时,它说:


Exception in thread "Main" java.lang.ArrayIndexOutOfBoundsException: 3


慕娘9325324
浏览 114回答 2
2回答

翻阅古今

ArrayIndexOutOfBoundsException声明您正在尝试访问不存在的元素和索引,因此,在这一行中:for&nbsp;(int&nbsp;column&nbsp;=&nbsp;0;&nbsp;&nbsp;DayOfTheMonth.length&nbsp;<&nbsp;4;&nbsp;column++)你已经指定去ForLoop 去无限,因为长度总是小于 4 所以你需要有column像这样的条件for&nbsp;(int&nbsp;column&nbsp;=&nbsp;0;&nbsp;&nbsp;column&nbsp;<&nbsp;DayOfTheMonth.length;&nbsp;column++)所以让它循环直到 3,因为它将从 0 开始并上升到 3。为了清楚起见,还有一件事是第一件事是行,第二件事是列,所以你有 3 行和 10 列,虽然它只是相关naming-problem但你应该清楚它。

尚方宝剑之说

这是2个问题。我无法回答第一个,因为您没有说明异常发生的位置,而且我不知道您所说的“绘制”数组是什么意思。其次,您的问题在这里(以及类似的地方):for&nbsp;(int&nbsp;column&nbsp;=&nbsp;0;&nbsp;DayOfTheMonth.length&nbsp;<&nbsp;4;&nbsp;column++)DayOfTheMonth.length将始终评估为 3,因此column将继续增加。你可能想要的是for&nbsp;(int&nbsp;column&nbsp;=&nbsp;0;&nbsp;column&nbsp;<&nbsp;DayOfTheMonth.length;&nbsp;column++)关于这是否是唯一的问题,我不作任何声明。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java