我有2个课程NewAray
和Disp
。
我有一个在NewAray
类中初始化的3D数组:
array3D= new int[][][]
{
{
{1,1,1,1,1,1,0,0},
{1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
.....
.....
哪个工作正常,我可以正确打印它。但是当我创建一个对象时
NewAray
中的Disp
类,并打印出来,给我一个NullPointerException
:NewAray aObj=new NewAray();
System.out.print(aObj.array3D[0][p][q]); //throws NPE
要么
System.out.print(aObj.array3D[0][0][0]);
在
Disp
类中。为什么?如何解决呢?编辑:NewAray类的代码要求:
public class NewAray {
static public int[][][] array3D;
public static void main(String... a)
{
array3D= new int[][][]
{
{
{1,1,1,1,1,1,0,0},
{1,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0}
}
};
int i,j,k;
for(i=0; i<1; i++){
for(j=0; j<8; j++){
for (k=0; k<8; k++ )
{
System.out.print(array3D[i][j][k]);
}
System.out.println();
}
System.out.println();
}
}
}
最佳答案
更换:
static public int[][][] array3D;
public static void main(String... a)
{
array3D= new int[][][]
{ // data
带有:
static public int[][][] array3D = new int[][][]
{ // data
目前,您仅在
main
方法中初始化数据,如果在程序的其他位置使用main
方法,则不会调用该数据。