数组未在构造函数中实例化
Array is not being Instantiated in Constructor
我不明白为什么我的数组没有在我的构造函数中实例化。
这是我的代码示例:
public class sandBox {
int array[];
int x;
public void sandBox() {
array = new int[5];
x = 0;
}
public static void main(String[] args) {
sandBox test = new sandBox();
int arrayTest[];
arrayTest = new int[10];
System.out.println(arrayTest.length);
System.out.print(test.x);
System.out.print(test.array.length);
}
}
这就是我的 运行 时间给我的:
----jGRASP exec: java sandBox
10
0
Exception in thread "main" java.lang.NullPointerException
at sandBox.main(sandBox.java:21)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
当然 arrayTest.length 打印正确,表明错误不在我的语法中。
test.x 也正确打印,表明我的构造函数 sandBox() 也 'worked' 因为它实例化了 x(一个 int)。
但是当我们需要打印 test.array.length 时,我得到了空指针错误。为什么?实例化的数组不是长度为5吗?
从您的 "constructor" 中删除 void
:)
太棒了!
正如 Jorn Vernee 指出的那样,我的构造函数不再是构造函数,因为我添加了一个 void!通过摆脱 void,所有问题都解决了!
我不明白为什么我的数组没有在我的构造函数中实例化。
这是我的代码示例:
public class sandBox {
int array[];
int x;
public void sandBox() {
array = new int[5];
x = 0;
}
public static void main(String[] args) {
sandBox test = new sandBox();
int arrayTest[];
arrayTest = new int[10];
System.out.println(arrayTest.length);
System.out.print(test.x);
System.out.print(test.array.length);
}
}
这就是我的 运行 时间给我的:
----jGRASP exec: java sandBox
10
0
Exception in thread "main" java.lang.NullPointerException
at sandBox.main(sandBox.java:21)
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
当然 arrayTest.length 打印正确,表明错误不在我的语法中。
test.x 也正确打印,表明我的构造函数 sandBox() 也 'worked' 因为它实例化了 x(一个 int)。
但是当我们需要打印 test.array.length 时,我得到了空指针错误。为什么?实例化的数组不是长度为5吗?
从您的 "constructor" 中删除 void
:)
太棒了!
正如 Jorn Vernee 指出的那样,我的构造函数不再是构造函数,因为我添加了一个 void!通过摆脱 void,所有问题都解决了!