Reputation: 69
I have asked a question about my code for a Game of Life Implementation. The suggested solution solved my problem but created a new one.
Now if I try to call the getCell()
method I get a java.lang.NullPointerException
.
How can I avoid this exception?
Link to my previous question with the corresponding code and solution code that I used:
How can I access the Cell Array in my getCell method? (Java)
Or if you just want the code:
public class GameMap {
private Cell[][] cellArray;
private static Cell[][] buildCellArray(int width, int height){
Cell[][] cellArray = new Cell[width][height];
int i;
int j;
for(i = 0; i < width; i++) {
for(j = 0; j < height; j++) {
cellArray[i][j] = new Cell();
}
}
return cellArray;
}
public GameMap(int sizeX, int sizeY) {
buildCellArray(sizeX, sizeY);
}
public Cell getCell(int posX, int posY){
return cellArray[posX][posY];
}
}
Upvotes: 2
Views: 109
Reputation: 298
Like Thilo mentioned, you currently return the new cell array that you create in the method, but you never assign your field 'cellArray' within GameMap. Instead, you define a new variable cellArray with the same name, store all of the associated values in there, return it, then don't use it.
There are quite a few ways to fix this. You could modify your constructor as such:
public GameMap(int sizeX, int sizeY) {
this.cellArray = buildCellArray(sizeX, sizeY);
}
This would set the value of the class's cellArray
field after you return from buildCellArray.
Another way would be to slightly change your declaration of cellArray
in your buildCellArray
method, and remove the static modifier on your method definition. Instead of saying:
Cell[][] cellArray = new Cell[width][height];
You could instead say:
cellArray = new Cell[width][height];
This would work because within your first example, you're creating a whole new variable (with the same name, but under a different scope). This means you don't reference your field cellArray
when you define everything for it, but only reference the local version you created inside of buildCellArray
. In this example though, you would be using the original field as your reference, instead of the local version of the variable.
Upvotes: 1
Reputation: 262794
buildCellArray(sizeX, sizeY);
That does indeed build a new array and returns it, but you are not assigning it to that field it needs to go to. You are just throwing away the result, and the field stays what it was (null
).
You need to do
cellArray = buildCellArray(sizeX, sizeY);
It is a bit confusing that you have a local variable with the same name as the field in your static method. But they are completely unrelated. Try to avoid that kind of shadowing. You could change the name to for example
private static Cell[][] buildCellArray(int width, int height){
Cell[][] newCellArray = new Cell[width][height];
Upvotes: 4