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

📄 ch10.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 2 页
字号:
</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>Applet8</TT> class from Java's <TT>Applet</TT>class.<BR>    Declare <TT>TextField</TT> objects called <TT>textField1</TT>and <TT>textField2.<BR></TT>    Override the <TT>Applet</TT> class's <TT>init()</TT>method.<BR>        Create the two <TT>TextField</TT> objects.<BR>        Add the two <TT>TextField</TT> objects to the applet.<BR>        Initialize the <TT>TextField</TT> objects to &quot;1&quot;and &quot;10.&quot;<BR>    Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR>        Print a prompt for the user.<BR>        Get the number from the first <TT>TextField</TT> object.<BR>        Convert the number from text to an integer.<BR>        Get the number from the second <TT>TextField</TT> object.<BR>        Convert the number from text to an integer.<BR>        Initialize the row counter.<BR>        Initialize the loop control variable, count.<BR>        Loop from the starting value to the ending value.<BR>            Initialize a string to <TT>&quot;Count = &quot;</TT>.<BR>            Add the loop counter to the text string.<BR>            Draw the text string in the applet's display area.<BR>            Increment the row counter.<BR>    Override the <TT>Applet</TT> class's <TT>action()</TT> method.<BR>        Tell Java to redraw the applet's display area.<BR>        Tell Java that the <TT>action()</TT> method finished successfully.</BLOCKQUOTE><HR><BLOCKQUOTE><B>Listing 10.3&nbsp;&nbsp;APPLET8.htmL: Applet8's HTML Document.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>&lt;title&gt;Applet Test Page&lt;/title&gt;&lt;h1&gt;Applet Test Page&lt;/h1&gt;&lt;applet    code=&quot;Applet8.class&quot;    width=250    height=350    name=&quot;Applet8&quot;&gt;&lt;/applet&gt;</PRE></BLOCKQUOTE><HR><P>When you run Applet8, type the starting value for the loop inthe first box and the ending value for the loop in the secondbox. (Don't press enter until you've entered both values.) Whenyou do, the program's <TT>while</TT> loop runs for the valuesyou selected, printing the value of the loop control variableeach time through the loop. For example, in Figure 10.1, the <TT>while</TT>loop has counted from 1 to 10 (the default values for the <TT>TextField</TT>controls). You can type any numbers you like, however. If youtyped 15 in the first box and 30 in the last box, the <TT>while</TT>loop will count from 15 to 30, as shown in Figure 10.2.<P><A HREF="f10-2.gif"><B> Figure 10.2 : </B><I>Applet8 will count however you tell it to.</I></A><P><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>If you enter a pair of numbers with a wide range, the applet's output will run off the bottom of the applet. This won't hurt anything, but you'll be unable to see the entire output. In addition, if you make the starting value greater than the ending value, no output will appear in the applet's display area. This is because the <TT>while</TT> loop's conditional expression never evaluates to true.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="TheIdowhileILoop"><FONT SIZE=5 COLOR=#Ff0000>The <I>do-while</I> Loop</FONT></A></H2><P>Java also features <TT>do-while</TT> loops. A <TT>do-while</TT>loop is much like a <TT>while</TT> loop, except a <TT>do-while</TT>loop evaluates its control expression at the end of the loop ratherthan at the beginning. So the body of the loop-the statementsbetween the beginning and end of the loop-is always executed atleast once. In a <TT>while</TT> loop, the body of the loop mayor may not ever get executed. Listing 10.4 shows how a <TT>do-while</TT>loop works.<HR><BLOCKQUOTE><B>Listing 10.4&nbsp;&nbsp;LST10_4.TXT: Using a </B><I>do-while</I><B>Loop.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>num = 0;do    ++num;while (num &lt; 10);</PRE></BLOCKQUOTE><HR><P>The difference between a <TT>do-while</TT> loop and a <TT>while</TT>loop are readily apparent when you look at the listing. As youcan see, the loop's conditional expression is at the end insteadof the beginning. That is, in the example listing, <TT>num</TT>will always be incremented at least once. After Java increments<TT>num</TT>, it gets to the <TT>while</TT> line and checks whether<TT>num</TT> is less than 10. If it is, program execution jumpsback to the beginning of the loop, where <TT>num</TT> gets incrementedagain. Eventually, <TT>num</TT> becomes equal to 10, causing theconditional expression to be false, and the loop ends.<H3><A NAME="ExampleUsingaIdowhileILoop">Example: Using a <I>do-while</I> Loop</A></H3><P>Near the beginning of this chapter, you saw an example of a <TT>while</TT>loop whose body contained multiple statements. By using bracesto mark off a program block, you can do the same thing with a<TT>do-while</TT> loop. Listing 10.5 shows how to create a multipleline <TT>do-while</TT> loop:<HR><BLOCKQUOTE><B>Listing 10.5&nbsp;&nbsp;LST10_5.TXT: A Multiple-Line </B><I>do-while</I><B>loop.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>num = 0;do{    ++num;    String s = String.valueOf(num);    g.drawString(&quot;num is now equal to:&quot;, 20, 40);    g.drawString(s, 20, 55); }while (num &lt; 10);</PRE></BLOCKQUOTE><HR><P><IMG ALIGN=RIGHT SRC="pseudo.gif" HEIGHT=94 WIDTH=94 BORDER=1><BLOCKQUOTE>Initialize the loop control variable.<BR>Begin the <TT>do-while</TT> loop.<BR>    Increment the loop control variable.<BR>    Create a string from the value of <TT>num.<BR></TT>    Display a message on the screen.<BR>    Display the value of <TT>num</TT>.<BR>    Determine whether to repeat the loop.</BLOCKQUOTE><H3><A NAME="ExampleUsingaIdowhileILoopinaProgram">Example: Using a <I>do-while</I> Loop in a Program</A></H3><P>Now it's time to put your knowledge of <TT>do-while</TT> loopsto the test. If you haven't yet picked up on the pattern, youmay be surprised to learn that the next applet is called Applet9.Applet9 looks and acts a lot like Applet8. In fact, as far asthe user is concerned, they are almost exactly the same program.However, the clever among you may have already guessed that Applet9uses a <TT>do-while</TT> loop in place of the <TT>while</TT> loop.This means that regardless of the values the user enters intothe applet's <TT>TextField</TT> controls, the applet will alwaysdisplay at least one line of text. Listing 10.6 is the applet.Modify the HTML document from Listing 10.3, replacing all occurrencesof Applet8 with Applet9, in order to run the new version of theapplet.<HR><BLOCKQUOTE><B>Listing 10.6&nbsp;&nbsp;Applet9.java: Source Code for Applet9.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet9 extends Applet{    TextField textField1;    TextField textField2;    public void init()    {        textField1 = new TextField(5);        textField2 = new TextField(5);        add(textField1);        add(textField2);        textField1.setText(&quot;1&quot;);        textField2.setText(&quot;10&quot;);    }    public void paint(Graphics g)    {        g.drawString(&quot;Enter start and end values above.&quot;, 50, 45);        String s = textField1.getText();        int start = Integer.parseInt(s);        s = textField2.getText();        int end = Integer.parseInt(s);        int row = 0;        int count = start;        do        {            s = &quot;Count = &quot;;            s += String.valueOf(count++);            g.drawString(s, 80, row * 15 + 70);            ++row;        }        while (count &lt;= end);    }    public boolean action(Event event, Object arg)    {        repaint();        return true;    }}</PRE></BLOCKQUOTE><HR><P>As long as the user always enters a lower value in the first boxand a higher value in the second, the Applet9 applet will performexactly as Applet8 did. However, the difference appears when thestarting value is greater than the ending value. Applet8 producedno text output at all under these conditions, because the <TT>while</TT>loop evaluates the condition before it executes the body of theloop. As Figure 10.3 shows, Applet9 always displays at least oneline of text output, because the loop is evaluated after its bodyis executed rather than before. In the figure, the user has entereda starting value that's higher than the ending value.<P><A HREF="f10-3.gif"><B> Figure 10.3 : </B><I>The do-while loop always executes at least once.</I></A><P><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>By using loops, you can easily program your applets to performrepetitive operations. Although loops may seem a little strangeto you at this point, you'll find more and more uses for themas you write your own applets. Just remember that a <TT>while</TT>loop may or may not ever execute depending on how the conditionalexpressions works out. On the other hand, a <TT>do-while</TT>loop always executes at least once because its conditional isevaluated at the end of the loop rather than at the start. Inthe next chapter, you'll learn about one last type of loop, calleda <TT>for</TT> loop. As you'll see, you use a <TT>for</TT> loopwhen you know exactly how many times a loop must execute.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>When do you use loops in a program?<LI>What is the body of a loop?<LI>How does Java determine when to stop looping?<LI>How many times is a <TT>while</TT> loop guaranteed to execute?<LI>Why is it important to initialize a loop control variable?<LI>What's an infinite loop?<LI>Compare and contrast <TT>while</TT> and <TT>do-while</TT>loops?<LI>How many times will the loop shown in Listing 10.7 execute?What will <TT>count</TT> equal when the loop finishes?</OL><HR><BLOCKQUOTE><B>Listing 10.7&nbsp;&nbsp;LST10_7.TXT: The Loop for Review Question8.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>int count = 10;do{    ++count;}while (count &lt;= 15);</PRE></BLOCKQUOTE><HR><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write a <TT>while</TT> loop that executes 20 times.<LI>Convert the <TT>while</TT> loop you wrote in exercise 1 toa <TT>do-while</TT> loop.<LI>Write a <TT>while</TT> loop that will result in an infiniteloop.<LI>Write a <TT>do-while</TT> loop that can never execute morethan once.<LI>Write a <TT>while</TT> loop that counts backwards from 20to 10.<LI>Modify Applet8 so that it totals all the numbers from theuser's selected starting value to the ending value. That is, ifthe user enters 10 and 15 as the starting and ending values, theapplet should sum 10, 11, 12, 13, 14, and 15, and then displaythe result. Name the program <TT>WhileApplet.java</TT>. Figure10.4 shows what the final applet should look like. (You can findthe solution to this programming problem in the CHAP07 folderof this book's CD-ROM.)<BR><A HREF="f10-4.gif"><B> Figure 10.4 : </B><I>This is what the WhileApplet applet should <r>look like.</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 + -