我无法处理对象的2D数组...
我有一个GameEngine类,我声明:
Tile[][] theBoard;
在课堂后期,我设置了董事会:
theBoard = new Tile[8][8];
prepareTheBoard();
prepareTheBoard方法:(也在同一个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]));
}
...
}
第一张照片给了我(正如预期的那样):
n:0长度:8
但第二次打印出错:
线程“main”中的异常 显示java.lang.NullPointerException
我做错了什么?为什么它会看到数组的长度,但我无法解决它?
提前致谢。
答案 0 :(得分:2)
您没有实例化2d阵列单元格。
theBoard = new Tile [8] [8];
它将创建2d数组的空值。您需要使用下面的新运算符实例化每个单元格。
theBoard [i] [j] = new Tile();
答案 1 :(得分:1)
在调用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]));
}