i'm trying to create an minesweeper game using this Class Diagram I'm stuck here for 2 hours and can't find any solution to it,while i'm trying to call the function in the GridData class,the NullPointerException always heppen,Also i can't change the element in an array, Anyone has a suggestion ?
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("");
}
}
Output
null null null
null null null
null null null
Doing new GridData[3][3];
will just get you the null
array. You'll have to initialize each element in it by doing:
for (i = 0; i < boardSize; i++) {
for (j = 0; j < boardSize; j++) {
board[i][j] = new GridData();
}
}
Once you initialize the array, you can proceed with rest of the code.
Here is the code snippet:
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();
}