我在尝试使用一种方法分别访问三角形数组时遇到问题,每次我尝试使用tarray[i][j]
时,除非在类创建过程中完成,否则我都会得到一个空指针异常,例如,我有一个get方法并且使用return tarray[0][0]
,即使它在创建过程中打印得很好,也只会抛出错误。
我知道我可能在做一些愚蠢的事情,但我只是想不通,
public class Triangular<A> implements Cloneable
{
private int inRa;
private A [][] tarray;
/**
* Constructor for objects of class Triangular
* @param indexRange - indices between 0 and indexRange-1 will be legal to index
* this a triangular array
* @throws IllegalArgumentException - if indexRange is negative
*/
public Triangular(int indexRange) throws IllegalArgumentException
{
inRa=indexRange;
int n = inRa;
int fill = 1;
Object [][] tarray = new Object [inRa + 1][];
for (int i = 0; i <= inRa; i++){
tarray[i] = new Object [n];
}
for (int i = 0; i < tarray.length; i++){
for (int j = 0; j + i < tarray[i].length; j++){
tarray[i][j + i] = fill;
fill ++;
}
}
for (int i = 0; i < tarray.length; i++) {
for (int j = 0; j + i < tarray[i].length; j++){
System.out.print(tarray[i][j + i] + " ");
}
System.out.println();
}
}
}
感谢您的帮助!
最佳答案
您无需初始化构造函数中tarray
字段的任何内容,而是初始化具有相同名称的局部变量;这个:
Object [][] tarray = new Object [inRa + 1][]; // doesn't access the tarray field
但是,您必须为
tarray
字段分配某些内容才能修复NPE。顺便说一句:最好不要使用与字段同名的局部变量。