Programming and Problem Solving with Java

(やまだぃちぅ) #1
12.1 T w o - Dimensional Arrays | 583

Column
number

Row
number

The first two lines of the following code fragment would create the two-dimensional ar-
ray shown in Figure 12.1, where the data in the table are floating-point numbers.


double[][] alpha;
alpha = new double[100][9];
String[][] beta;
beta = new String[10][10];


The first dimension specifies the number of rows, and the second dimension specifies
the number of columns. Once the two-dimensional array has been created,alpha.lengthand
beta.lengthgive the number of rows in each array.


Accessing Individual Components


To access an individual component of the alphaarray, we use two expressions (one for each
dimension) to specify its position. We place each expression in its own pair of brackets next
to the name of the array:


alpha[0][5]= 36.4;


The syntax template for accessing a two-dimensional array component follows:

As with one-dimensional arrays, each index expression must result in an integer value be-
tween 0 and the number of slots in that dimension minus one.
Let’s look now at some examples. Here is the declaration of a two-dimensional array with
364 integer components (52 7 = 364):


int[][] hiTemp;
hiTemp = new int[52][7];


Here hiTempis an array with 52 rows and 7 columns. Each place in the array (each component)
can contain an intvalue. Our intention is that the array hold high temperatures for each day


Array-Name [ Index-Expression ] [Index-Expression]

Two-Dimensional-Array-Component-Access

Data-Type[][] Array-Name;

Two-Dimensional-Array-Declaration
Free download pdf