我在尝试使用方法分别访问我的三角形数组时出现问题,每次我尝试使用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();
}
}
}
谢谢你的帮助!
答案 0 :(得分:1)
您没有在构造函数中初始化tarray
字段的任何内容,而是初始化同名的局部变量;这一个:
Object [][] tarray = new Object [inRa + 1][]; // doesn't access the tarray field
但是,您必须为tarray
字段指定一些东西来修复NPE。
BTW:最好不要使用与字段名称相同的局部变量。