我在寻址一个对象的2D数组时遇到了麻烦…
我有一个类GameEngine,我声明:
Tile[][] theBoard;
后来在课堂上,我设置了黑板:
theBoard = new Tile[8][8];
prepareTheBoard();
prepareTheBoard方法:(也在同一个类中声明- 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]));
}
...
}
第一次打印给我(如预期的):
n: 0长度:8
但是第二次打印给出了一个错误:
main线程异常java.lang.NullPointerException
我做错了什么?为什么它能看到数组的长度,但我不能处理它?
您没有实例化2d数组单元格。
theBoard = new Tile[8][8];
它将创建2d的空数组。您需要使用如下的new操作符实例化每个单元格。
theBoard[i][j] = new Tile();
在调用setPiece()方法之前,必须像这样在for循环中初始化数组中的对象:
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]));
}