PDA

View Full Version : Is there any way to modify a null object in an Array?




bigrell486
Apr 15, 2007, 05:23 PM
Hi. I'm trying to place an object into an array but I keep getting null pointer exceptions is there anyway around this?

Heres the code:

public class Board {
Tile tile[][] ;
int crntx = 0;
int crnty = 0;
int goalx;
int goaly;

public Board(int numRows, int numCols){
goalx = numRows - 1;
goaly = numCols - 1;
Tile tile[][] = new Tile[numRows][numCols];


public Boolean play(Tile piece){
tile[crntx][crnty] = piece;
toString();
return null;

}

public Boolean isWinner(){
return false;

}

public Boolean isDone(){
Boolean done = false;
return done;

}

public int numRows(){
return goalx + 1;

}

public int numCols(){
return goaly + 1;

}

public String toString(){
for(int y = 0; y < goaly + 1; y++) {
for(int x = 0; x < goalx + 1; x++){
try {
System.out.print(tile[x][y].toString()+" ");
} catch(NullPointerException e){
System.out.print(". ");
}
}
System.out.println();
}
return null;

}
}


Is there any way I can fix this?



darkwing
Apr 15, 2007, 05:40 PM
Your problem is in the Board constructor. You are saying "Tile tile[][] = ..." which is causing you to make a new variable named "tile" in that scope.

Change to:

tile = new Tile[numRows][numCols];