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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 7 Arrays 345<br />

25<br />

26 outputArea.append( "\nValues in array2 by row are\n" );<br />

27 buildOutput( array2 );<br />

28 }<br />

29<br />

30 // append rows and columns of an array <strong>to</strong> outputArea<br />

31 public void buildOutput( int array[][] )<br />

32 {<br />

33 // loop through array's rows<br />

34 for ( int row = 0; row < array.length; row++ ) {<br />

35<br />

36 // loop through columns of current row<br />

37 for ( int column = 0;<br />

38 column < array[ row ].length;<br />

39 column++ )<br />

40 outputArea.append( array[ row ][ column ] + " " );<br />

41<br />

42 outputArea.append( "\n" );<br />

43 }<br />

44 }<br />

45 }<br />

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

The program declares two arrays in method init. The declaration of array1 (line<br />

20) provides six initializers in two sublists. The first sublist initializes the first row of the<br />

array <strong>to</strong> the values 1, 2 and 3. The second sublist initializes the second row of the array <strong>to</strong><br />

the values 4, 5 and 6. The declaration of array2 (line 21) provides six initializers in three<br />

sublists. The sublist for the first row explicitly initializes the first row <strong>to</strong> have two elements<br />

with values 1 and 2, respectively. The sublist for the second row initializes the second row<br />

<strong>to</strong> have one element with value 3. The sublist for the third row initializes the third row <strong>to</strong><br />

the values 4, 5 and 6.<br />

Line 24 of method init calls method buildOutput (defined at lines 31–44) <strong>to</strong><br />

append each array’s elements <strong>to</strong> outputArea (a JTextArea). Method buildOutput<br />

specifies the array parameter as int array[][] <strong>to</strong> indicate that the method receives a<br />

double-subscripted array as an argument. Note the use of a nested for structure (lines 34–<br />

43) <strong>to</strong> output the rows of a double-subscripted array. In the outer for structure, the expression<br />

array.length determines the number of rows in the array. In the inner for structure,<br />

the expression array[ row ].length determines the number of columns in the<br />

current row of the array. This condition enables the loop <strong>to</strong> determine the exact number of<br />

columns in each row.<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!