📄 ch13.htm
字号:
<HTML><HEAD><TITLE>developer.com - Reference</TITLE><META NAME="Author" CONTENT="developer.com"><META NAME="Keywords" CONTENT="javascript, ActiveX, VRML, Push, channel,push channel, applet, directory, news, community, developer, internet,intranet, java, java applet, J++, javabeans, java products, tools, javatools, JDK, java development kit, java development environment, JIT,JavaPlan, enterprise tools, JVM, Java Virtual Machine, Java resources, API,browser, java documentation, CDF, Common Desktop Format, RDF, ResourceDescription Framework, Netcaster, Netcast, Castanet, meta-language, metadata,solaris, Solaris, SUN, CGI, Perl, Oracle, database, network, Netscape API,Apache, apache, SSL, mSQL, Netscape, Fasttrack, FastTrack,industry standard, ActiveX bridge, web, internet, site, sitedesign, microsoft, active server pages, asp, iis, nt, win95, 95, html, cgi,frontpage, business, corporate, vbscript, javascript, activex, isapi,database, access, sql, server, www, 3.0, 3.01, 3.02, 3.03, 3.04, 4.0,4.0b2, 4.01, 4.03, 4.04, connection, online, commerce, publisher,publishing, publish, webmaster, dynamic html, dhtml, windows 98, netscape,netscape software, shareware, magazines, jobs, japan, free, freeware, freestuff"><META NAME="description" CONTENT="Developer.com is the leading onlineservice for developers. It includes Gamelan, the official directory for Java, as wellas news, information, tutorials, and directories for other Internet technologiesincluding ActiveX, JavaScript, perl, VRML, Java Beans, push technologies, andother Internet and intranet technologies. Developer.com is also the home ofDeveloper Direct, the Professional Developer's Store, where developers canpurchase and download thousands of Web, authoring and other developmentproducts at some of today's lowest prices."><META NAME="distribution" CONTENT="global"><META NAME="resource-type" CONTENT="document"><META NAME="language" CONTENT="en"></HEAD><BODY BACKGROUND="/images/curve_r-wide.gif" BGCOLOR="#FFFFFF" TEXT="#000000" LINK="#DD0000" VLINK="#999999" ALINK="#FF0000"><TABLE><TR><TD VALIGN=TOP WIDTH=120><A HREF="/" ><IMG SRC="/images/masthead_r.gif" WIDTH="100" HEIGHT="78" BORDER="0"ALT="Developer.com Logo"></a></TD><TD><a target="resource window" href="http://adserver.developer.com/cgi-bin/accipiter/adclick.exe/AREA=DCBAN.REF/DT=null"><img src="http://adserver.developer.com/cgi-bin/accipiter/adserver.exe/AREA=DCBAN.REF/DT=null" HEIGHT="60" WIDTH="468" ALT="Click here to support our advertisers"><BR><CENTER>Click here to support our advertisers</CENTER></a></TD></TR></TABLE><!--outer table--><TABLE><!--outer table--><TR><!--outer table--><TD VALIGN="TOP"><!--navbar info --><table><tr><td><A HREF="http://www.developerdirect.com/" ><IMG SRC="/images/button_s.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>SHOPPING</b></font></a></td></tr><tr><td><A HREF="/community/jobs/c_jobs.html"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>JOB BANK</B></font></a></td></tr><tr><td><A HREF="http://www.classifieds2000.com/cgi-cls/display.exe?Developer+computer+searchcomputercategories"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>CLASSIFIEDS</B></font></a></td></tr><tr><td><A HREF="/directories/directories.html"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>DIRECTORIES</B></font></a></td></tr><tr><td><A HREF="/reference/"><IMG SRC="/images/button_r.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>REFERENCE</B></font></a><br><a href="/reference/r_library.html"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000">Online Library</a></font></td></tr><tr><td><A HREF="/classroom/"><IMG SRC="/images/button_r.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>LEARNING CENTER</B></font></a></td></tr><tr><td><A HREF="/journal/"><IMG SRC="/images/button_n.gif" width="15" height="11" BORDER="0"><B><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000">JOURNAL</font></B></a></td></tr><tr><td><A HREF="/news/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>NEWS CENTRAL</b></font></a></td></tr><tr><td><A HREF="/downloads/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>DOWNLOADS</b></font></a></td></tr><tr><td><A HREF="/community/" ><IMG SRC="/images/button_c.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><B>COMMUNITY</B></font></a></td></tr><tr><td><A HREF="/calendar/"><IMG SRC="/images/button_d.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>CALENDAR</b></font></a></td></tr><tr><td><A HREF="/about/"><IMG SRC="/images/button_a.gif" width="15" height="11" BORDER="0"><FONT FACE="Arial, Helvetica" SIZE="-1" color="#000000"><b>ABOUT US</b></a></font></td></tr></table><table><tr><td><form action="/subscribe/list.cgi" method=post ><img src="/images/rule.gif" width="100" height="2"><br><B><FONT FACE="Arial, Helvetica" SIZE="-1">Journal:</b></font><br><input name='email' value='your e-mail' size="11"><input type='hidden' name='state' value='Subscribe'></td></tr><tr><td><input type='submit' value='Subscribe'><br><font size="-1">Get the weekly email highlights from the most popular journal for developers!<br><a href="http://www.developer.com/subscribe.html">Current issue</a><img src="/images/rule.gif" width="100" height="2"><input type='hidden' name='name' value='New Subscriber'></FORM></td></tr></table><!--/navbar--><font size="-1"><A HREF="http://www.developer.com">developer.com</a><BR><A HREF="http://www.developerdirect.com">developerdirect.com</a><BR><A HREF="http://www.htmlgoodies.com">htmlgoodies.com</a><BR><A HREF="http://www.javagoodies.com">javagoodies.com</a><br><A HREF="http://www.jars.com">jars.com</a><BR><a href="http://www.intranetjournal.com">intranetjournal.com</a><br><a href="http://www.javascripts.com">javascripts.com</a><br></font><!--outer table--></TD><!--outer table--><TD VALIGN="TOP"><BLOCKQUOTE><P><img src="/images/header_r.gif" width="440" height="50"><P><MAP NAME ="header_r2.gif.map"><AREA SHAPE ="RECT" HREF ="/reference/author.html" COORDS ="361,0,440,29"><AREA SHAPE ="RECT" HREF ="/reference/basic.html" COORDS ="254,0,360,29"><AREA SHAPE ="RECT" HREF ="/reference/help.html" COORDS ="183,0,251,29"><AREA SHAPE ="RECT" HREF ="/reference/cool.html" COORDS ="100,0,181,29"><AREA SHAPE ="RECT" HREF ="/reference/mybook.html" COORDS ="0,0,100,29"></MAP><MAP NAME ="header_r1.gif.map"><AREA SHAPE ="RECT" HREF ="/reference/personalize.html" COORDS ="339,0,439,29"></MAP><p><font face="Arial,Helvetica" size="-1" color="#006666"><A HREF="/reference/r_library.html"><B>All Categories</A> :</B><b><A HREF="/reference/r_java.html">Java</A></b></font><p><META><H1><FONT SIZE=6 COLOR=#Ff0000>Chapter 13</FONT></H1><H1><FONT SIZE=6 COLOR=#Ff0000>Arrays</FONT></H1><HR><P><CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER><UL><LI><A HREF="#AnIntroductiontoArrays">An Introduction to Arrays</A><UL><LI><A HREF="#ExampleCreatinganArray">Example: Creating an Array</A><LI><A HREF="#ExampleUsingaVariableasaSubscript">Example: Using a Variable as a Subscript</A></UL><LI><A HREF="#MultidimensionalArrays">Multidimensional Arrays</A><UL><LI><A HREF="#ExampleCreatingaTwoDimensionalArray">Example: Creating a Two-Dimensional Array</A></UL><LI><A HREF="#ExampleUsingTwoDimensionalArraysinanApplet">Example: Using Two-Dimensional Arrays in an Applet</A><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>As you've learned by now, using variables makes your programsflexible. Thanks to variables, you can conveniently store datain your programs and retrieve it by name. You can also get inputfrom your program's user. The best thing about variables is thatthey can constantly change value. (They're called variables, afterall, because they're variable.)<P>Until now, you've learned about various types of numerical variables,including integers, long integers, floating-point, and doublefloating-point variables. You also know about string variables,which can hold text. Now that you have a good understanding ofthese data types, it's time to explore one last data type-a handydata structure called an array.<H2><A NAME="AnIntroductiontoArrays"><FONT SIZE=5 COLOR=#Ff0000>An Introduction to Arrays</FONT></A></H2><P>Often in your programs, you'll want to store many values thatare related in some way. Suppose you manage a bowling league,and you want to keep track of each player's average. One way todo this is to give each player a variable in your program, asshown in Listing 13.1. Figure 13.1 shows the applet running underAppletviewer.<P><A HREF="f13-1.gif"><B> Figure 13.1 : </B><I>This is Applet16 running under Appletviewer.</I></A><P><HR><BLOCKQUOTE><B>Listing 13.1 Applet16.java: Using Variables to TrackScores.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet16 extends Applet{ TextField textField1, textField2, textField3; int avg1, avg2, avg3; public void init() { textField1 = new TextField(5); textField2 = new TextField(5); textField3 = new TextField(5); add(textField1); add(textField2); add(textField3); textField1.setText("0"); textField2.setText("0"); textField3.setText("0"); } public void paint(Graphics g) { g.drawString("Your bowlers' averages are: ", 50, 80); String s = textField1.getText(); g.drawString(s, 75, 110); avg1 = Integer.parseInt(s); s = textField2.getText(); g.drawString(s, 75, 125); avg2 = Integer.parseInt(s); s = textField3.getText(); g.drawString(s, 75, 140); avg3 = Integer.parseInt(s); } public boolean action(Event event, Object arg) { repaint(); return true; }}</PRE></BLOCKQUOTE><HR><P>When you run Applet16, you can enter bowling scores into the threeboxes at the top of the applet's display area. After you enterthese averages, they're displayed on-screen as well as copiedinto the three variables <TT>avg1</TT>, <TT>avg2</TT>, and <TT>avg3</TT>.<P>Nothing too tricky going on here, right?<P>Now examine the listing. Remember in <A HREF="ch10.htm" >Chapter 10</A>, "The <TT>while</TT>and <TT>do-while</TT> Loops," when you learned to keep aneye out for repetitive program code? How about all those callsto <TT>getText()</TT>, <TT>drawString()</TT>, and <TT>valueOf()</TT>in Listing 13.1? The only real difference between them is thespecific bowler's score that's being manipulated. If you couldfind some way to make a loop out of this code, you could shortenthe program significantly. How about a <TT>for</TT> loop thatcounts from 1 to 3?<P>But how can you use a loop when you're stuck with three differentvariables? The answer is an array. An array is a variable thatcan hold more than one value. When you first studied variables,you learned that a variable is like a box in memory that holdsa single value. Now, if you take a bunch of these boxes and putthem together, what do you have? You have an array. For example,to store the bowling averages for your three bowlers, you'd needan array that can hold three values. You could call this array<TT>avg</TT>. You can even create an array for a set of objectslike the <TT>TextField</TT> objects Applet16 uses to get bowlingscores from the user. You could call this array <TT>textField</TT>.<P>Now you have an array called <TT>avg</TT> that can hold threebowling averages and an array called <TT>textField</TT> that canhold three <TT>TextField</TT> objects. But how can you retrieveeach individual average or object from the array? You do thisby adding something called a subscript to the array's name. Asubscript (also called an index) is a number that identifies theelement of an array in which a value is stored. For example, torefer to the first average in your <TT>avg</TT> array, you'd write<TT>avg[0]</TT>. The subscript is the number in square brackets.In this case, you're referring to the first average in the array(array subscripts always start from zero.) To refer to the secondaverage, you'd write avg<TT>[1]</TT>. The third average is <TT>avg[2]</TT>.<P>If you're a little confused, look at Figure 13.2, which showshow the <TT>avg[]</TT> array might look in memory. In this case,the three bowling averages are 145, 192, and 160. The value of<TT>avg[0]</TT> is 145, the value of <TT>avg[1]</TT> is 192, andthe value of <TT>avg[2]</TT> is 160.<P><A HREF="f13-2.gif"><B> Figure 13.2 : </B><I>An array can hold many values of the same type.</I></A><P><H3><A NAME="ExampleCreatinganArray">Example: Creating an Array</A></H3><P>Suppose that you need an array that can hold 30 floating-pointnumbers. First, you'd declare the array like this:<BLOCKQUOTE><PRE>float numbers[];</PRE></BLOCKQUOTE><P>Another way to declare the array is to move the square bracketsto after the data type, like this:<BLOCKQUOTE><PRE>float[] numbers;</PRE></BLOCKQUOTE><P>After declaring the array, you need to create it in memory. Javalets you create arrays only using the <TT>new</TT> operator, likethis:<BLOCKQUOTE><PRE>numbers = new float[30];</PRE></BLOCKQUOTE><P>The last step is to initialize the array, a task that you mightperform using a <TT>for</TT> loop:<BLOCKQUOTE><PRE>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -