John Kl. John Kl. - 2 months ago 6
Java Question

Can´t address 2d array of objects

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.

Answer

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