Reputation: 49
I have a 2D array that I need to "reset" each time a tic tac toc game is started. I call a method and loop through the array setting all the elements to Zero. But this defeats the purpose of my program because i need to have all the elements empty/null again.
public static char[][] initializeGame(char[][] gameBoard) {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
gameBoard = null; //<--THIS IS THE THING AM TRYING TO NULL @ gameBoard[row][column]
}
}
return gameBoard;
}
How can I set the elements of gameBoard
to null?
Upvotes: 0
Views: 17147
Reputation: 450
You cannot set a char
to null
. You can only set it to 0
. null
is a pointer value, char
is a primitive numeric value. Pointers don't fit into primitive values.
So..
gameBoard[row][col]=0
.. should do the trick.
Upvotes: 0
Reputation: 26321
If you are lazy, you could reinstantiate a new array.
gameBoard = new int[3][3];
I would not recommend this approach, as it is less performant and leaks memory if it is not correctly collected.
A more elegant choice would be to reinitialize the whole array, you dont need to set the values to null
since they are of type char
for(int r = 0; r < gameBoard.length; r++)
for(int c = 0; c < gameBoard[r].length; c++)
gameBoard[r][c] = '\0'; //Null character
But hey, why bother writing three lines of code, when there's a prebuilt Java utility method that will help you out?
Arrays.fill(gameBoard, '\0'); //Fills the array with Null characters
Upvotes: 0
Reputation: 5496
If you are asking how to change the values of individual elements in a 2D array to null, you would do this:
gameBoard[row][col] = null;
But since you have a 2D char array, you can't do that as char is a primitive type and does not allow having a null value. You could use a different char value to represent empty, or you could make a 2D array have Character objects, but a better solution might be a 2D array of an enumeration type such as:
public enum TicTacToeSquareValue { x, o, empty }
.... later on:
gameBoard[row][col] = TicTacToeSquareValue.empty;
Upvotes: 0