I'm having an issue with trying to access my triangular array separately using a method, each time i try to use tarray[i][j]
I get a null pointer exception unless it's done within the class creation, for example I have a get method and have used return tarray[0][0]
and it just throws me the error even though it prints out fine within the creation.
I know I'm probably doing something stupid but I just can't figure it out,
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();
}
}
}
thank you for your help!
You don't initialize anything to the tarray
field in the constructor, you initialize a local variable of the same name; this one:
Object [][] tarray = new Object [inRa + 1][]; // doesn't access the tarray field
You have to assign something to the tarray
field, however, to fix the NPE.
BTW: It's better not to use local variables that have the same name as a field.