1

I´m having trouble addressing 2D array of an object...

I have a class GameEngine, where I declare:

Tile[][] theBoard;

Later in the class, I set the board up:

theBoard = new Tile[8][8];
prepareTheBoard();

prepareTheBoard method: (also declared in the same calss - GameEngine)

public void prepareTheBoard(){

    int n = 0;

    for(n = 0; n < 8; n++){
        System.out.println("n: " + n + " length: " + theBoard[1].length);
        System.out.println("theBoard : " + theBoard[1][1].isEmpty());
        theBoard[1][n].setPiece(new Piece(PieceColor.WHITE, Pieces.PAWN, theBoard[1][n]));
        theBoard[6][n].setPiece(new Piece(PieceColor.BLACK, Pieces.PAWN, theBoard[6][n]));
    }
...
}

The first print gives me (as expected):

n: 0 length: 8

But the second print gives an error:

Exception in thread "main" java.lang.NullPointerException

What am I doing wrong? Why does it see the length of array, but I can´t address it?

Thanks in advance.

Jan Kl.
  • 69
  • 2
  • 13
  • 2
    The array has a size of 8, but each of the 8 indexes contain null, since you never put anything inside it, and you are calling `isEmpty` on a null `Tile` . . – Arnaud Sep 30 '16 at 12:36
  • Just a random tip. Try debugging if you are using IDE. And try step over code. :) – mubeen Sep 30 '16 at 12:49

2 Answers2

2

You didn't instantiate the 2d array cells.

theBoard = new Tile[8][8];

It will create 2d array of nulls. You need to instantiate every cell using new operator like below.

theBoard[i][j] = new Tile();

Aman Agrawal
  • 95
  • 1
  • 1
  • 10
1

Before you call the setPiece() method, you have to initialize the object in array like this in the for-loop:

for(n = 0; n < 8; n++) {
    theBoard[1][n] = new Tile();
    theBoard[6][n] = new Tile();
    System.out.println("n: " + n + " length: " + theBoard[1].length);
    System.out.println("theBoard : " + theBoard[1][1].isEmpty());
    theBoard[1][n].setPiece(new Piece(PieceColor.WHITE, Pieces.PAWN, theBoard[1][n]));
    theBoard[6][n].setPiece(new Piece(PieceColor.BLACK, Pieces.PAWN, theBoard[6][n]));
}
static-max
  • 739
  • 10
  • 19