⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch11.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 2 页
字号:
<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&nbsp;11</FONT></H1><H1><FONT SIZE=6 COLOR=#Ff0000>The <I>for</I> Loop</FONT></H1><HR><P><CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER><UL><LI><A HREF="#IntroducingtheIforILoop">Introducing the <I>for</I> Loop</A><LI><A HREF="#ExampleUsingaIforILoop">Example: Using a <I>for</I> Loop</A><LI><A HREF="#ExampleUsingaIforILoopinaProgram">Example: Using a <I>for</I> Loop in a Program</A><LI><A HREF="#ChangingtheIncrementValue">Changing the Increment Value</A><LI><A HREF="#ExampleLoopingwithDifferentIncrements">Example: Looping with Different Increments</A><LI><A HREF="#UsingVariablesinLoops">Using Variables in Loops</A><LI><A HREF="#ExampleControllingIforILoopswithVariables">Example: Controlling <I>for</I> Loops with Variables</A><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>In the previous chapter, you got an introduction to looping. Alongthe way, you learned about <TT>while</TT> and <TT>do-while</TT>loops, which are an important part of the Java language. Javaalso supports another type of loop, called a <TT>for</TT> loop,that enables you to specify exactly how many times the loop shouldbe executed. In this chapter, you learn to write <TT>for</TT>loops, as well as how to incorporate them into your Java programs.<H2><A NAME="IntroducingtheIforILoop"><FONT SIZE=5 COLOR=#Ff0000>Introducing the <I>for</I> Loop</FONT></A></H2><P>Probably the most often-used loop in programming is the <TT>for</TT>loop, which instructs a program to perform a block of code a specifiednumber of times. There are many applications for a <TT>for</TT>loop, including tasks such as reading through a list of data itemsor initializing an array. (You'll learn about arrays in Chapter13, &quot;Arrays.&quot;) You could, for example, use a <TT>for</TT>loop to instruct your computer to print 10,000 address labels,reading a new address from a file each time through the loop andsending that address to the printer. Because you don't currentlyhave an address file, however, let's say you want to print a nameon the screen 10 times. Listing 11.1 shows one way to do this.<HR><BLOCKQUOTE><B>Listing 11.1&nbsp;&nbsp;LST11_1.TXT: Printing a Name 10 Times.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>g.drawString(&quot;Alfred Thompson&quot;, 50, 50);g.drawString(&quot;Alfred Thompson&quot;, 50, 65);g.drawString(&quot;Alfred Thompson&quot;, 50, 80);g.drawString(&quot;Alfred Thompson&quot;, 50, 95);g.drawString(&quot;Alfred Thompson&quot;, 50, 110);g.drawString(&quot;Alfred Thompson&quot;, 50, 125);g.drawString(&quot;Alfred Thompson&quot;, 50, 140);g.drawString(&quot;Alfred Thompson&quot;, 50, 155);g.drawString(&quot;Alfred Thompson&quot;, 50, 170);g.drawString(&quot;Alfred Thompson&quot;, 50, 185);</PRE></BLOCKQUOTE><HR><P>If you were to add the lines shown in Listing 11.1 to your Javaapplet's <TT>paint()</TT> method, you'd see something like Figure11.1. As you can see, you've accomplished the task at hand, whichis printing a name 10 times. However, you haven't done it in themost efficient way.<P><A HREF="f11-1.gif"><B> Figure 11.1 : </B><I>This applet prints a name 10 times without using a loop.</I></A><P><P>Look at Listing 11.1. See all those calls to <TT>drawString()</TT>?As a computer programmer, whenever you see program code containingmany identical instructions, a little bell should go off in yourhead. When you hear this little bell, you should do one of twothings:<OL><LI>Answer your telephone.<LI>Say to yourself, &quot;This looks like a good place for aloop.&quot;</OL><P>Having many lines in your program containing identical instructionsmakes your program longer than necessary and wastes valuable memory.It also shows poor programming style. Unless you want your programmingfriends to snicker behind your back, learn to replace redundantprogram code with program loops.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>TIP</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>To produce programs that are tightly written, shorter, and faster, always try to replace repetitive program code with program loops.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="ExampleUsingaIforILoop"><FONT SIZE=5 COLOR=#Ff0000>Example: Using a <I>for</I> Loop</FONT></A></H2><P>Listing 11.1 can be streamlined easily by using a <TT>for</TT>loop, as shown in Listing 11.2. The output of the second versionis identical to the first, but now the listing is shorter andcontains no redundant code.<HR><BLOCKQUOTE><B>Listing 11.2&nbsp;&nbsp;LST11_2.TXT: Using a </B><I>for</I><B>Loop to Print a Name 10 Times.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>int row = 0;for (int x=0; x&lt;10; ++x)    g.drawString(&quot;Al Thompson&quot;, 25, 50 + (x * 15));</PRE></BLOCKQUOTE><HR><P>Look at the program line beginning with the keyword <TT>for</TT>.The loop starts with this line. The word <TT>for</TT> tells Javathat you're starting a <TT>for</TT> loop. There are actually threeelements inside the parentheses. The first part, <TT>x=1</TT>,is called the initialization section. The second part, <TT>x&lt;10</TT>,is called the condition; the last part, <TT>++x</TT>, is calledthe increment.<P>All three sections of the <TT>for</TT> loop, which are separatedby semicolons, reference the loop-control variable <TT>x</TT>.The loop-control variable, which can have any integer-variablename, is where Java stores the current loop count. Notice thatthe loop-control variable must have been previously declared asan <TT>int</TT> (integer) variable. You can place this declarationas part of the initialization part of the command.<P>The initialization section of the <TT>for</TT> statement is usedto initialize the loop-control variable that controls the action.The condition section represents a Boolean condition that shouldbe equal to true for the loop to continue execution. Finally,the increment, which is the third part of the statement, is anexpression describing how to increment the control variable. Thestatement after the <TT>for</TT> statement is executed each timethe loop's conditional expression is found to be true.<P>Suppose you want to modify Listing 11.2 to print the name 20 times.What would you change? If you answered, &quot;I'd change the 10in the <TT>for</TT> line to 20,&quot; you win the Programmer ofthe Week award. If you answered, &quot;I'd change my socks,&quot;you better find a different book to read.<H2><A NAME="ExampleUsingaIforILoopinaProgram"><FONT SIZE=5 COLOR=#Ff0000>Example: Using a <I>for</I> Loop in a Program</FONT></A></H2><P>The best way to learn about any programming construct is to useit in a program. Listing 11.3 is a short applet called Applet10that uses a <TT>for</TT> loop to display a given name 10 times.Listing 11.4 is the HTML document that runs the applet, whereasFigure 11.2 shows the applet running under Appletviewer.<P><A HREF="f11-2.gif"><B> Figure 11.2 : </B><I>This applet displays, 10 <r>times, whatever name the user types.</I></A><P><HR><BLOCKQUOTE><B>Listing 11.3&nbsp;&nbsp;Applet10.java: Using a </B><I>for<B></B></I><B>Loop in an Applet.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet10 extends Applet{    TextField textField1;    public void init()    {        textField1 = new TextField(20);        add(textField1);        textField1.setText(&quot;Moe Howard&quot;);    }    public void paint(Graphics g)    {        g.drawString(&quot;Enter a name above.&quot;, 70, 45);        String s = textField1.getText();        for (int x=0; x&lt;10; ++x)            g.drawString(s, 80, x * 15 + 70);    }    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>Applet10</TT> class from Java's <TT>Applet</TT>class.<BR>    Declare a <TT>TextField</TT> object called <TT>textField1</TT>.<BR>    Override the <TT>Applet</TT> class's <TT>init()</TT> method.<BR>        Create the <TT>TextField</TT> object.<BR>        Add the <TT>TextField</TT> object to the applet.<BR>        Initialize the text in the <TT>TextField</TT> object to

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -