📄 ch13.htm
字号:
Array.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>table[0][0] = 0;table[1][0] = 1;table[2][0] = 2;table[3][0] = 3;table[0][1] = 4;table[1][1] = 5;table[2][1] = 6;table[3][1] = 7;table[0][2] = 8;table[1][2] = 9;table[2][2] = 10;table[3][2] = 11;table[0][3] = 12;table[1][3] = 13;table[2][3] = 14;table[3][3] = 15;</PRE></BLOCKQUOTE><HR><P>You refer to a value stored in a two-dimensional array by usingsubscripts for both the column and row in which the value youwant is stored. For example, to retrieve the value 11 from the<TT>table[][]</TT> array shown in Figure 13.4, you use a linelike this:<BLOCKQUOTE><PRE>int value = table[3][2];</PRE></BLOCKQUOTE><P>A quick way to initialize a two-dimensional array is to use nested<TT>for</TT> loops, as shown in Listing 13.7.<HR><BLOCKQUOTE><B>Listing 13.7 LST13_11.TXT: Using Loops to Initializea Two-Dimensional Array.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>for (int x=0; x<3; ++x){ for (int y=0; y<3; ++y) { table[x][y] = 5; }}</PRE></BLOCKQUOTE><HR><P>If you've never seen nested loops before, you're about to discoverhow handy they can be. In the case of Listing 13.7, the outsideloop (the <TT>x</TT> loop) starts first, setting <TT>x</TT> to0. But the body of the loop is another loop. So the inside loop(the <TT>y</TT> loop) starts, setting <TT>y</TT> to 0, which bringsthe program to the line that initializes an element of the array.Because <TT>x</TT> and <TT>y</TT> both equal 0, the array element<TT>table[0][0]</TT> gets set to 5. Then the inside loop sets<TT>y</TT> to 1, which means <TT>table[0][1]</TT> gets set to5. When the inner loop finishes, the program branches back tothe outer loop, setting <TT>x</TT> to 1. The inner loop repeatsagain, only this time with <TT>x</TT> equal to 1 and <TT>y</TT>going from 0 to 2. Finally, when both loops finish, the entirearray is initialized.<P>Of course, to create the array shown in Figure 13.4 with loops,you have to be a little more tricky, as shown in Listing 13.8.Work through each loop to see how the array gets initialized.<HR><BLOCKQUOTE><B>Listing 13.8 LST13_8.TXT: Initializing the ArrayElements to Different Values.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>for (int x=0; x<3; ++x){ for (int y=0; y<3; ++y) { table[x][y] = x + y * 4; }}</PRE></BLOCKQUOTE><HR><H3><A NAME="ExampleCreatingaTwoDimensionalArray">Example: Creating a Two-Dimensional Array</A></H3><P>Suppose that you need a table-like array that can hold 80 integersin eight columns and 10 rows. First, you'd declare the array likethis:<BLOCKQUOTE><PRE>int numbers[][];</PRE></BLOCKQUOTE><P>After declaring the array, you need to create it in memory, likethis:<BLOCKQUOTE><PRE>numbers = new int[8][10];</PRE></BLOCKQUOTE><P>The last step is to initialize the array, probably using nested<TT>for</TT> loops:<BLOCKQUOTE><PRE>for (int x=0; x<8; ++x) for (int y=0; y<10; ++y) numbers[x][y] = 0;</PRE></BLOCKQUOTE><P>These lines initialize the <TT>numbers[][]</TT> array to all zeroes.<H2><A NAME="ExampleUsingTwoDimensionalArraysinanApplet"><FONT SIZE=5 COLOR=#Ff0000>Example: Using Two-Dimensional Arrays in an Applet</FONT></A></H2><P>To be sure you understand how arrays work, you'll put a two-dimensionalarray to work in a program called Applet18. The Applet18 appletcreates and initializes a two-dimensional array with six columnsand eight rows. (Try to imagine the elements of this array asthe rows and columns of a spreadsheet.) The program then printsthe contents of the array in the Applet's display area, so youcan see that the array truly holds the values to which it wasinitialized. Listing 13.9 is the program, whereas Figure 13.5shows the applet running under the Appletviewer application.<P><A HREF="f13-5.gif"><B> Figure 13.5 : </B><I>This is Applet18 running under Appletviewer.</I></A><P><HR><BLOCKQUOTE><B>Listing 13.9 Applet18.java: Using a Two-DimensionalArray.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet18 extends Applet{ int table[][]; public void init() { table = new int[6][8]; for (int x=0; x<6; ++x) for (int y=0; y<8; ++y) table[x][y] = x+y*6; } public void paint(Graphics g) { for (int x=0; x<6; ++x) for (int y=0; y<8; ++y) { String s = String.valueOf(table[x][y]); g.drawString(s, 50+x*25, 50+y*15); } }}</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Tell Java that the program uses classes in the <TT>awt</TT> package.<BR>Tell Java that the program uses classes in the <TT>applet</TT>package.<BR>Derive the <TT>Applet18</TT> class from Java's <TT>Applet</TT>class.<BR> Declare a two-dimensional integer array.<BR> Override the <TT>Applet</TT> class's <TT>init()</TT> method.<BR> Create an array with six columns and eight rows.<BR> Loop from 0 to 5.<BR> Loop from 0 to 7.<BR> Initialize the currently indexed array element.<BR> Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR> Loop from 0 to 5.<BR> Loop from 0 to 7.<BR> Convert the array element to a string.<BR> Display the array element's value.</BLOCKQUOTE><P>Notice in <TT>init()</TT> and <TT>paint()</TT> how the nestedloops don't have curly braces like the example shown in Listing13.8. This is because when you have only one statement in a programblock, the curly braces are optional. In Applet18's <TT>init()</TT>method, the outside loop contains only one statement, which isthe inner <TT>for</TT> loop. The inner <TT>for</TT> loop alsocontains only a single statement, which is the line that initializesthe currently indexed element of the array. In the <TT>paint()</TT>method, the outer loop contains only one statement, which is theinner <TT>for</TT> loop. However, the inner loop contains twostatements, so the curly braces are required in order to markoff that program block.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Arrays are a powerful data structure that enable you to storemany related values using the same variable name. A one-dimensionalarray is a lot like a list of values that you can access by tellingJava the appropriate subscript (or index). But because array subscriptsalways start at 0, the subscript is always one less than the numberof the associated element. You can also create multidimensionalarrays (or, to be more precise, arrays of arrays). A two-dimensionalarray is organized much like a table. To access the elements ofa two-dimensional array, you need two subscripts. The first subscriptidentifies the column of the table and the second identifies therow.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What is an array?<LI>Why are arrays easier to use than a bunch of related variables?<LI>What is an array subscript? How is a subscript like an index?<LI>What is a two-dimensional array?<LI>If you had an array of 50 integers, what is the largest validsubscript?<LI>What happens if you try to access a nonexistent array element?<LI>Describe why a <TT>for</TT> loop is appropriate for accessingan array?<LI>How would you use <TT>for</TT> loops to initialize a two-dimensionalarray?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Declare an array that can hold 50 integers.<LI>Write the code that creates the array you declared in exercise1.<LI>Write a <TT>for</TT> loop that initializes the array to thevalues 50 through 99.<LI>Write the Java code to declare and create a two-dimensionalarray with 10 columns and 15 rows.<LI>Write nested <TT>for</TT> loops that initialize the arrayfrom exercise 4 to the values 0 through 149.<LI>Write the Java code needed to display, in table form, thevalues in the array from exercise 5.<LI>Modify Applet17 so that it stores and displays not only thebowlers' scores, but also the bowlers' names. Create three <TT>TextField</TT>objects to enable the user to enter names and three for enteringthe scores. Name the program <TT>ScoreApplet.java</TT>. Figure13.6 shows what the final applet should look like at startup.(You can find the solution to this programming problem in theCHAP13 folder of this book's CD-ROM.)<BR><A HREF="f13-6.gif"><B> Figure 13.6 : </B><I>This is the ScoreApplet applet running under Appletviewer.</I></A><P></OL><HR><HR WIDTH="100%"></P></CENTER><!-- reference library footer #1--></CENTER><IMG SRC="/images/rule.gif" WIDTH="460" HEIGHT="5" VSPACE="5"ALT="Ruler image"><br><FONT SIZE="-1">Contact <a href="mailto:reference@developer.com">reference@developer.com</a> with questions or comments.<br><a href="/legal/">Copyright 1998</a> <a href="http://www.earthweb.com" target="_top">EarthWeb Inc.</a>, All rights reserved.<BR>PLEASE READ THE <a href="/reference/usage.html">ACCEPTABLE USAGE STATEMENT</a>.<BR>Copyright 1998 Macmillan Computer Publishing. All rights reserved.</FONT></BLOCKQUOTE><!--outer table--><TD VALIGN="TOP"><!--right side ads --><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD1.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD1.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCAD2.REF" alt="Click here for more info"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCAD2.REF" alt="Click here for more info" height="88" width="88" border="0"></a><P></td></tr></table></BODY></HTML>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -