我正在尝试使用此Class Diagram创建一个扫雷游戏 我被困在这里2个小时并且找不到任何解决方案,而我正在尝试调用GridData类中的函数,NullPointerException总是为heppen,我也无法更改数组中的元素,任何人有建议吗?
public GridData[][] board ;
public BomberGame(int boardSize,int bombNo){
int i = 0;
int j = 0;
if(boardSize < 3)
board = new GridData[3][3] ;
else
board = new GridData[boardSize][boardSize];
for (i = 0; i < boardSize; i++)
{
for (j = 0; j < boardSize; j++)
{
//board[i][j]BomberGame = 0 ;// here is the problem i can't mess with any element in array
board[i][j].setIsOpen(true); // after doing NullPointerException occur
board[i][j].gridIsOpen();
System.out.print(board[i][j]+" ");
}
System.out.println("");
}
}
输出
null null null
null null null
null null null
答案 0 :(得分:0)
执行new GridData[3][3];
只会获得null
数组。您必须通过执行以下操作初始化其中的每个元素:
for (i = 0; i < boardSize; i++) {
for (j = 0; j < boardSize; j++) {
board[i][j] = new GridData();
}
}
初始化阵列后,您可以继续使用其余代码。
以下是代码段:
for (i = 0; i < boardSize; i++) {
for (j = 0; j < boardSize; j++) {
board[i][j] = new GridData();
board[i][j].setIsOpen(true);
board[i][j].gridIsOpen();
System.out.print(board[i][j] + " ");
}
System.out.println();
}
答案 1 :(得分:-1)
board = new GridData[3][3];
在这里,您只创建数组。现在,还需要分配数组中的每个元素。像:
board[i][j] = new GridData();