26.07.2013 Views

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

Java How to Program Fourth Edition - DCC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

344 Arrays Chapter 7<br />

creates integer array b with row 0 containing two elements (1 and 2) and row 1 containing<br />

three elements (3, 4 and 5).<br />

A multiple-subscripted array with the same number of columns in every row can be<br />

allocated dynamically. For example, a 3-by-4 array is allocated as follows:<br />

int b[][];<br />

b = new int[ 3 ][ 4 ];<br />

In this case, we the literal values 3 and 4 <strong>to</strong> specify the number of rows and number of columns,<br />

respectively. Note that programs also can use variables <strong>to</strong> specify array dimensions.<br />

As with single-subscripted arrays, the elements of a double-subscripted array are initialized<br />

when new creates the array object.<br />

A multiple-subscripted array in which each row has a different number of columns can<br />

be allocated dynamically as follows:<br />

int b[][];<br />

b = new int[ 2 ][ ]; // allocate rows<br />

b[ 0 ] = new int[ 5 ]; // allocate columns for row 0<br />

b[ 1 ] = new int[ 3 ]; // allocate columns for row 1<br />

The preceding code creates a two-dimensional array with two rows. Row 0 has five columns<br />

and row 1 has three columns.<br />

The applet of Fig. 7.15 demonstrates initializing double-subscripted arrays in declarations<br />

and using nested for loops <strong>to</strong> traverse the arrays (i.e., manipulate every element of<br />

the array).<br />

1 // Fig. 7.15: InitArray.java<br />

2 // Initializing multidimensional arrays<br />

3<br />

4 // <strong>Java</strong> core packages<br />

5 import java.awt.Container;<br />

6<br />

7 // <strong>Java</strong> extension packages<br />

8 import javax.swing.*;<br />

9<br />

10 public class InitArray extends JApplet {<br />

11 JTextArea outputArea;<br />

12<br />

13 // set up GUI and initialize applet<br />

14 public void init()<br />

15 {<br />

16 outputArea = new JTextArea();<br />

17 Container container = getContentPane();<br />

18 container.add( outputArea );<br />

19<br />

20 int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } };<br />

21 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } };<br />

22<br />

23 outputArea.setText( "Values in array1 by row are\n" );<br />

24 buildOutput( array1 );<br />

Fig. Fig. 7.15 7.15 Initializing multidimensional arrays (part 1 of 2).<br />

© Copyright 1992–2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!