[英]How to initialize a two-dimensional array?
I'm having trouble initializing an array. 我在初始化数组时遇到问题。 When I try to draw the Array I'm getting a NullPointerException
. 当我尝试绘制数组时,出现NullPointerException
。
I need to access the class where I've declared the array from another class, that's why it's static
. 我需要访问从另一个类声明了数组的类,这就是为什么它是static
的原因。
Here's my code: 这是我的代码:
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++;
}
}
}
}
}
Another problem is that, when I try to access the method trough my main class, it says: 另一个问题是,当我尝试通过主类访问方法时,它说:
Exception in thread "Main" java.lang.ArrayIndexOutOfBoundsException: 3
ArrayIndexOutOfBoundsException
states you are trying to access an Element from and Index that does not exists so, ArrayIndexOutOfBoundsException
指出您正在尝试从中访问元素,而Index不存在,
In this line: 在这一行:
for (int column = 0; DayOfTheMonth.length < 4; column++)
You have specified to go For
Loop to go infinite because the length will always be less than 4 so you need to have column
in condition like 您已指定将For
Loop设为无限,因为长度将始终小于4,因此您需要将column
为类似
for (int column = 0; column < DayOfTheMonth.length; column++)
So Make it loop until 3, as it will start from 0 and go up to 3. 因此,使其循环直到3,因为它将从0开始直到3。
And 1 more thing for your clarity the 1st Thing is Row and Second is column, so you have 3 rows and 10 columns although its just related to naming-problem
but you should be clear about it. 为了清楚起见,还有1件事是第一行是列,第二是列,因此您有3行和10列,尽管它仅与naming-problem
有关,但您应该对此有所了解。
This is 2 questions. 这是两个问题。 I can't answer the first because you don't say where the exception happens, and I don't know what you mean by "draw" the array. 我无法回答第一个问题,因为您没有说异常发生在哪里,而且我也不知道“绘制”数组的意思。
For the second, your problem is here (and in similar places): 第二,您的问题在这里(和类似的地方):
for (int column = 0; DayOfTheMonth.length < 4; column++)
DayOfTheMonth.length
will always evaluate to 3, so column
will keep increasing. DayOfTheMonth.length
将始终计算为3,因此column
将继续增加。 What you probably want is 您可能想要的是
for (int column = 0; column < DayOfTheMonth.length; column++)
I make no claims as to whether this is the only problem. 我没有断言这是否是唯一的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.