Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

bigrell486

macrumors 6502
Original poster
Jul 10, 2006
331
101
Home
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?
 
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];
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.