Two-Dimensional Arrays
When constructing a two-dimensional array, you specify how many rows and columns you need:
final int ROWS = 3;
final int COLUMNS = 3;
String[][] board = new String[ROWS][COLUMNS];
You access elements with an index pair a[i][j]
board[i][j] = "x";
Traversing Two-Dimensional Arrays
It is common to use two nested loops when filling or searching:
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++)
board[i][j] = " ";
Click here for TicTacToe program.
How do you declare and initialize a 4-by-4 array of integers?
Answer:
int[][]
array = new int[4][4];
How do you count the number of spaces in the tic-tac-toe board?
Answer:
int count = 0;
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++)
if (board[i][j] == ' ') count++;