fotonphorces
fotonphorces

Reputation: 15

NullPointerException returning an array that will filled in a different method

I am getting a NullPointerException when the getCave method is called when it tries to return the 2D array. I have not been able to find a solution online. I can get the program to run without the exception by replacing the return with a new Cave that is not an array but that would not fit my needs. Here is a simplified version of my code:

import java.util.Random;


public class Board {

    public static final int DEFAULT_ROWS = 10;
    public static final int DEFAULT_COLS = 10;


    Cave[][] caveArray = new Cave[DEFAULT_ROWS+2][DEFAULT_COLS+2];


    public Board(int rows, int cols){

        Random rand = new Random();


                for (int j = 1; j < (cols+1); j++) {

                    for (int i = 1; i < (rows+1); i++) {

                        Cave temp;
                        temp = new Cave(i, j);

                        int rnum = rand.nextInt(100)+1;


                        if (rnum > 50) {
                                caveArray[i][j]=temp;
                                caveArray[i][j].makeBlocked(); 
                        }


                        else if(rnum <=50) {
                                caveArray[i][j]=temp;
                                caveArray[i][j].makeOpen();
                        }
                    }
                }           
    }

    public Cave getCave(int r, int c){

        return caveArray[r][c];
    }

}

here is the caller:

private void newGame() {
    // Set up the game board.
    gameBoard = new Board(DEFAULT_ROWS, DEFAULT_COLS);

    // Set up the 3 characters.
    characters = new ArrayList<Character>();

    // Add the adventurer (always in the top left).
    characters.add(new Adventurer(gameBoard.getCave(0, 0)));
    selected = 0; // Initially select the adventurer.
}

which calls:

public class Adventurer extends Character{

Adventurer(Cave initLoc) {
    super(initLoc);


}

which calls:

public abstract class Character implements CaveWorker{

protected Cave location;

public Character(Cave initLoc){
    location = initLoc;

    location.setOccupied(true);
}

Upvotes: 0

Views: 122

Answers (1)

Makoto
Makoto

Reputation: 106440

The only explanation that I can offer without observing a stack trace (those are really helpful, more times than not) is that if you attempt to index into caveArray[0][c], or even caveArray[r][0] there's not going to be anything there.

You have two options - either use the fact that arrays will start at index 0 (it's not so bad), or preemptively place a Cave object in row 0 and column 0 that serves no real purpose. Aligning with (0,0) would be the easier choice, though.

Upvotes: 1

Related Questions