📄 ch13.htm
字号:
for (int x=0; x<30; ++x) numbers[x] = (float)x;</PRE></BLOCKQUOTE><P>These lines of Java source code initialize the <TT>numbers[]</TT>array to the numbers 0.0 to 29.0. Notice how the loop only goesup to 29. This is because, although there are 30 elements in the<TT>numbers[]</TT> array, those elements are indexed startingwith 0, rather than 1. That is, the subscript is always one lessthan the number of the element you're accessing. The first elementhas a subscript of 0, the second a subscript of 1, the third asubscript of 2, and so on.<H3><A NAME="ExampleUsingaVariableasaSubscript">Example: Using a Variable as a Subscript</A></H3><P>As you learned in a previous chapter, most numerical literalsin a Java program can be replaced by numerical variables. Supposeyou were to use the variable <TT>x</TT> as the subscript for thearray <TT>avg[]</TT>. Then (based on the averages in Figure 13.2)if the value of <TT>x</TT> is 1, the value of avg[x] is 192. Ifthe value of <TT>x</TT> is 3, the value of <TT>avg[x]</TT> is160.<P>Now take one last, gigantic, intuitive leap (c'mon, you can doit) and think about using your subscript variable <TT>x</TT> asboth the control variable in a <TT>for</TT> loop and the subscriptfor the <TT>avg[]</TT> and <TT>textField</TT> arrays. If you usea <TT>for</TT> loop that counts from 0 to 2, you can handle allthree averages with much less code than in the original program.Listing 13.2 shows how this is done.<HR><BLOCKQUOTE><B>Listing 13.2 Applet17.java: Using Arrays.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet17 extends Applet{ TextField textField[]; int avg[]; public void init() { textField = new TextField[3]; avg = new int[3]; for (int x=0; x<3; ++x) { textField[x] = new TextField(5); add(textField[x]); textField[x].setText("0"); } } public void paint(Graphics g) { g.drawString("Your bowlers' averages are: ", 50, 80); for (int x=0; x<3; ++x) { String s = textField[x].getText(); g.drawString(s, 75, 110 + x*15); avg[x] = Integer.parseInt(s); } } public boolean action(Event event, Object arg) { repaint(); return true; }}</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>Applet17</TT> class from Java's <TT>Applet</TT>class.<BR> Declare <TT>TextField</TT> and <TT>int</TT> arrays.<BR> Override the <TT>Applet</TT> class's <TT>init()</TT> method.<BR> Create the <TT>textField</TT> and <TT>int</TT> arrayswith three elements each.<BR> Loop from 0 to 2.<BR> Create a new <TT>TextField</TT> object and store itin the array.<BR> Add the new <TT>TextField</TT> object to the applet.<BR> Set the new <TT>TextField</TT> object's text.<BR> Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR> Display a line of text.<BR> Loop from 0 to 2.<BR> Get the text from the currently indexed <TT>TextField</TT>object.<BR> Draw the retrieve text on the applet's display area.<BR> Convert the value and store it in the integer array.<BR> Override the <TT>Applet</TT> object's <TT>action()</TT> method.<BR> Force Java to redraw the applet's display area.<BR> Tell Java everything went okay.</BLOCKQUOTE><P>At the beginning of Listing 13.2, you'll see a couple of strangenew variable declarations that look like this:<BLOCKQUOTE><PRE>TextField textField[];int avg[];</PRE></BLOCKQUOTE><P>These declarations are much like other declarations you've seen,except both of the variable names end with a set of square brackets.The square brackets tell Java that you're declaring arrays ratherthan conventional variables.<P>Once you have the arrays declared, you must create them. In Applet17,this is done like this:<BLOCKQUOTE><PRE>textField = new TextField[3];avg = new int[3];</PRE></BLOCKQUOTE><P>Here you use the <TT>new</TT> operator to create the arrays. Totell Java the type of arrays to create, you follow <TT>new</TT>with the data type and the size of the array in square brackets.In other words, the first line above creates an array that canhold three <TT>TextField</TT> objects. The second line createsan array that can hold three integers.<P>Once you have your arrays created, you can use a loop to reducethe amount of code needed to initialize the arrays. For example,the long way to initialize the arrays (without using a loop) wouldlook something like Listing 13.3:<HR><BLOCKQUOTE><B>Listing 13.3 LST13_3.TXT: Initializing an Arraywithout Looping.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>textField[0] = new TextField(5);add(textField[0]);textField[0].setText("0");textField[1] = new TextField(5);add(textField[1]);textField[1].setText("0");textField[2] = new TextField(5);add(textField[2]);textField[2].setText("0");</PRE></BLOCKQUOTE><HR><P>As you learned, however, you can use a variable-specifically,a loop control variable-as the array subscript. That's what Applet17does, which enables it to initialize the <TT>textField</TT> arrayas shown in Listing 13.4.<HR><BLOCKQUOTE><B>Listing 13.4 LST13_4.TXT: Initializing an ArrayUsing a Loop.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>for (int x=0; x<3; ++x){ textField[x] = new TextField(5); add(textField[x]); textField[x].setText("0");}</PRE></BLOCKQUOTE><HR><P>The first time through the loop, <TT>x</TT> is equal to 0, sothat element 0 (the first element) of the <TT>textField</TT> arrayis being manipulated. The next time through the loop, <TT>x</TT>is 1, so that element 1 of the array is being manipulated in thebody of the loop. Finally, when <TT>x</TT> is 2, the program takescare of the third array element. As you can see, using a loopwith an array can greatly simplify handling a group of relatedvalues. Imagine how many lines of source code you'd save if thearray had 1,000 elements instead of only three. To accommodatethe larger array, you'd only have to change <TT>x<3</TT> to<TT>x<1000</TT> in the first line of the <TT>for</TT> loop.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>CAUTION</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Be careful not to try accessing a nonexistent array element. For example, in Listing 13.4, if you tried to access <TT>textField[3]</TT>, you'd be beyond the boundaries of the array. Java will generate an exception when this happens, which means your applet may or may not perform the way you want it to. (You'll learn more about exceptions in <A HREF="ch30.htm" >Chapter 30</A>, "Exceptions.")</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The <TT>init()</TT> method isn't the only place Applet17 takesadvantage of a loop to handle the program's arrays. In the <TT>paint()</TT>method, you can see the loop shown in Listing 13.5.<HR><BLOCKQUOTE><B>Listing 13.5 LST13_5.TXT: The </B><I>for</I><B>Loop from the </B><I>paint( )</I><B> Method.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>for (int x=0; x<3; ++x){ String s = textField[x].getText(); g.drawString(s, 75, 110 + x*15); avg[x] = Integer.parseInt(s);}</PRE></BLOCKQUOTE><HR><P>This loop simplifies the printing of the bowlers' scores and theloading of the <TT>avg[]</TT> array with the scores. Again, imaginehow much time and space you'd save if the arrays in question hadthousands of elements rather than only three. It's at times likethose that you really learn to appreciate arrays.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>The memory locations that make up an array are called <I>elements</I> of the array. For example, in an array named <TT>numbers[]</TT>, <TT>numbers[0]</TT> is the first element of the array, <TT>numbers[1]</TT> is the second element, and so on. The reason <TT>numbers[0]</TT> is the first element of the array is because of the number 0 inside the subscript.It is the number inside the subscript that defines which array location is being referred to.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="MultidimensionalArrays"><FONT SIZE=5 COLOR=#Ff0000>Multidimensional Arrays</FONT></A></H2><P>So far, you've looked at simple arrays that hold their data ina list. However, most programming languages also support multidimensionalarrays, which are more like tables than lists. For example, takea look at Figure 13.3. The first array in the figure is a one-dimensionalarray, which is like the arrays you've used so far in this chapter.The next type of array in the figure is two-dimensional, whichworks like the typical spreadsheet type of table you're used toseeing.<P><A HREF="f13-3.gif"><B> Figure 13.3 : </B><I>Arrays can have more than one dimension.</I></A><P><P>Although Java doesn't support multidimensional arrays in the conventionalsense, it does enable you to create arrays of arrays, which amountto the same thing. For example, to create a two-dimensional arrayof integers like the second array in Figure 13.3, you might usea line of code like this:<BLOCKQUOTE><PRE>int table[][] = new int[4][4];</PRE></BLOCKQUOTE><P>This line of Java code creates a table that can store 16 values-fouracross and four down. The first subscript selects the column andthe second selects the row. To initialize such an array with values,you might use the lines shown in Listing 13.6, which would giveyou the array shown in Figure 13.4.<P><A HREF="f13-4.gif"><B> Figure 13.4 : </B><I>Here's the two-dimensional array as initialized in Listing 13.6.</I></A><P><HR><BLOCKQUOTE><B>Listing 13.6 LST13_6.TXT: Initializing a Two-Dimensional
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -