我有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();
}
}
}
答案 0 :(得分:1)
array3D
时必须实例化{p> NewAray
:
public class NewAray {
static public int[][][] array3D = {...};
// + main
}
答案 1 :(得分:0)
替换:
static public int[][][] array3D;
public static void main(String... a)
{
array3D= new int[][][]
{ // data
使用:
static public int[][][] array3D = new int[][][]
{ // data
目前,您只在main
方法中初始化数据,如果您在程序中的其他位置使用main
方法,则不会调用该数据。
答案 2 :(得分:0)
因为数组尚未初始化。你是在main()中初始化它,它不会在Disp类中被调用。
答案 3 :(得分:0)
要解决和清理代码,需要考虑几点:
如果要访问另一个类中的实例变量,最好在NewArray类中使用getter方法。
public int getVal(int dim1, int dim2, int dim3) {
return this.array3D[dim1][dim2][dim3]
}
即使是家庭作业问题,干净的代码也避免了许多问题。