Java Reference
In-Depth Information
7.6 Two-Dimensional Arrays
Arrays and array lists can store linear sequences. Occasionally you want to store
collections that have a two-dimensional layout. The traditional example is the
tic-tac-toe board (see Figure 6 ).
Two-dimensional arrays form a tabular, two-dimensional arrangement. You access
elements with an index pair a[i][j] .
Such an arrangement, consisting of rows and columns of values, is called a
two-dimensional array or matrix. When constructing a two-dimensional array, you
specify how many rows and columns you need. In this case, ask for 3 rows and 3
columns:
final int ROWS = 3;
final int COLUMNS = 3;
String[][] board = new String [ROWS][COLUMNS];
This yields a two-dimensional array with 9 elements
board[0][0] board[0][1] board[0][2]
board[1][0] board[1][1] board[1][2]
board[2][0] board[2][1] board[2][2]
To access a particular element, specify two subscripts in separate brackets:
board[i][j] = "x";
When filling or searching a two-dimensional array, it is common to use two nested
loops. For example, this pair of loops sets all elements in the array to spaces.
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++)
board[i][j] = " ";
Search WWH ::




Custom Search