Skip to content
Advertisement

How to avoid java.lang.NullPointerException in my Code?

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];
    }
}

Advertisement

Answer

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];
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement