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

📄 ch11.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 2 页
字号:
&quot;Moe Howard.&quot;<BR>    Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR>        Display a prompt for the user.<BR>        Get the name from the <TT>TextField</TT> object.<BR>        Loop ten times.<BR>            Draw the name in the applet's display area.<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 11.4&nbsp;&nbsp;APPLET10.htmL: The HTML Document ThatRuns Applet10.<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;Applet10.class&quot;    width=250    height=250    name=&quot;Applet10&quot;&gt;&lt;/applet&gt;</PRE></BLOCKQUOTE><HR><P>The Applet10 applet is well explained in the pseudocode followingListing 11.3. However, notice how the loop counter <TT>x</TT>works in this program. Although the <TT>for</TT> loop executes10 times, the largest value stored in <TT>x</TT> will be 9. Thisis because the loop counter starts at 0, and counts 0, 1, 2, 3,4, 5, 6, 7, 8, and 9. You might at first expect <TT>x</TT> toend up being equal to 10, Watch out for this sort of thing inyour Java programs, especially if you use the value of the loopcounter within the body of the loop or elsewhere in the program.Applet10 uses the loop counter to determine the row at which toprint the next name. Keep in mind that, because <TT>x</TT> isdeclared as part of the <TT>for</TT> loop's program block, itcan't be accessed outside of that block.<H2><A NAME="ChangingtheIncrementValue"><FONT SIZE=5 COLOR=#Ff0000>Changing the Increment Value</FONT></A></H2><P>The previous example of a <TT>for</TT> loop increments the loopcounter by 1. But suppose you want a <TT>for</TT> loop that countsfrom 5 to 50 by fives? This could be useful if you need to usethe loop counter to display a value, which needs to be incrementedby a different number.  You can do this by changing the sectionsof the <TT>for</TT> loop, like this.<BLOCKQUOTE><PRE>for (x=5; x&lt;=50; x+=5)</PRE></BLOCKQUOTE><P>This loop doesn't start counting at 1. Rather, the loop variablebegins with a value of 5. Then, thanks to the <TT>x+=5</TT> statement,the loop variable is incremented by 5 each time through the loop.Therefore, <TT>x</TT> goes from 5 to 10, from 10 to 15, and soon up to 50, resulting in ten loops.<P>You can also use a <TT>for</TT> loop to count backwards, likethis:<BLOCKQUOTE><PRE>for (x=50; x&gt;=5; x-=5)</PRE></BLOCKQUOTE><P>Notice that in the initialization part of the <TT>for</TT> statement,the higher value is used. Notice also that the increment clauseuses a decrement operator, which causes the loop count to be decremented(decreased) rather than incremented.<H2><A NAME="ExampleLoopingwithDifferentIncrements"><FONT SIZE=5 COLOR=#Ff0000>Example: Looping with Different Increments</FONT></A></H2><P>If you're a little confused, take a look at Listing 11.5, whichshows the Java source code for a small applet called Applet11.This applet's <TT>paint()</TT> method contains two <TT>for</TT>loops, one that counts upward by fives and one that counts downwardby fives. Each time through the loop, the program prints out thevalue of the loop control variable, so that you can see exactlywhat's going on inside the loops. To run this applet, use theHTML document from the previous applet, but replace all occurrencesof Applet10 with Applet11. Figure 11.3 shows Appletviewer runningthe Applet11 applet.<P><A HREF="f11-3.gif"><B> Figure 11.3 : </B><I>You can use for loops to count forward or backward by any amount that you like.</I></A><P><HR><BLOCKQUOTE><B>Listing 11.5&nbsp;&nbsp;Applet11.java: Using Different Incrementswith </B><I>for</I><B> Loops.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet11 extends Applet{    public void paint(Graphics g)    {        int row = 0;        for (int x=5; x&lt;=40; x+=5)        {            String s = &quot;Loop counter = &quot;;            s += String.valueOf(x);            g.drawString(s, 80, row * 15 + 15);            ++row;        }        for (int x=40; x&gt;=5; x-=5)        {            String s = &quot;Loop counter = &quot;;            s += String.valueOf(x);            g.drawString(s, 80, row * 15 + 15);            ++row;        }    }}</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>Applet11</TT> class from Java's <TT>Applet</TT>class.<BR>    Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR>        Initialize the row counter.<BR>        Begin the first <TT>for</TT> loop.<BR>            Create the basic display string.<BR>            Add the loop counter value to the display string.<BR>            Show the string in the applet's display area.<BR>            Increment the row counter.<BR>        Start the second <TT>for</TT> loop.<BR>            Create the basic display string.<BR>            Add the loop counter value to the display string.<BR>            Show the string in the applet's display area.<BR>            Increment the row counter.</BLOCKQUOTE><H2><A NAME="UsingVariablesinLoops"><FONT SIZE=5 COLOR=#Ff0000>Using Variables in Loops</FONT></A></H2><P>Just as you can substitute variables for most numerical valuesin a program, you can also substitute variables for the literalsin a <TT>for</TT> loop. In fact, you'll probably use variablesin your loop limits as often as you use literals, if not more.Here's an example of how to use variables to control your <TT>for</TT>loops:<BLOCKQUOTE><PRE>for (x=start; x&lt;=end; x+=inc)</PRE></BLOCKQUOTE><P>In this partial <TT>for</TT> loop, the loop control variable <TT>x</TT>starts off at the value of the variable <TT>start</TT>. Each timethrough the loop, Java increments <TT>x</TT> by the value storedin the variable <TT>inc</TT>. Finally, when <TT>x</TT> is greaterthan the value stored in <TT>end</TT>, the loop ends. As you cansee, using variables with <TT>for</TT> loops (or any other kindof loop, for that matter) enables you to write loops that workdifferently based on the state of the program.<H2><A NAME="ExampleControllingIforILoopswithVariables"><FONT SIZE=5 COLOR=#Ff0000>Example: Controlling <I>for</I> Loops with Variables</FONT></A></H2><P>For this chapter's last applet, you'll apply everything you'velearned about <TT>for</TT> loops. The Applet12 applet, shown inListing 11.6, enables you to experiment with different starting,ending, and increment values for the <TT>for</TT> loop containedin the applet's <TT>paint()</TT> method. Enter the starting valuefor the loop in the first box, then enter the ending and incrementvalues in the second and third boxes. Don't press Enter untilyou've filled in all three boxes with the values you want. Whenyou press Enter, the <TT>action()</TT> method takes over, tellingJava to repaint the applet's display area using the new values.Figure 11.5 shows Applet12 running under the Appletviewer application.<P><A HREF="f11-4.gif"><B> Figure 11.4 : </B><I>Applet12 enables you to experiment with different starting, ending, and increment values.</I></A><P><HR><BLOCKQUOTE><B>Listing 11.6&nbsp;&nbsp;Applet12.java: Advanced </B><I>for<B></B></I><B>Loops.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet12 extends Applet{    TextField textField1;    TextField textField2;    TextField textField3;    public void init()    {        textField1 = new TextField(5);        textField2 = new TextField(5);        textField3 = new TextField(5);        add(textField1);        add(textField2);        add(textField3);        textField1.setText(&quot;1&quot;);        textField2.setText(&quot;10&quot;);        textField3.setText(&quot;1&quot;);    }    public void paint(Graphics g)    {        g.drawString(&quot;Enter loop starting, ending,&quot;, 50, 45);        g.drawString(&quot;and increment values above.&quot;, 50, 60);        String s = textField1.getText();        int start = Integer.parseInt(s);        s = textField2.getText();        int end = Integer.parseInt(s);        s = textField3.getText();        int inc = Integer.parseInt(s);        int row = 0;        for (int x=start; x&lt;=end; x+=inc)        {            String s2 = &quot;Loop counter = &quot;;            s2 += String.valueOf(x);            g.drawString(s2, 50, row * 15 + 85);            ++row;        }    }    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>Applet12</TT> class from Java's <TT>Applet</TT>class.<BR>    Declare three <TT>TextField</TT> objects as fields of theclass.<BR>    Override the <TT>Applet</TT> class's <TT>init()</TT> method.<BR>        Create the three <TT>TextField</TT> objects.<BR>        Add the three <TT>TextField</TT> objects to the applet.<BR>        Initialize the <TT>TextField</TT> objects with their startingtext.<BR>    Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR>        Display a prompt to the user.<BR>        Get the entered text and convert it to integers.<BR>        Initialize the row counter.<BR>        Begin the <TT>for</TT> loop.<BR>            Create the basic display string.<BR>            Add the loop counter value to the display string.<BR>            Show the 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 method finished successfully.</BLOCKQUOTE><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>The <TT>for</TT> loop is a versatile programming construct thatenables you to create loops that run from a given starting valueto a given ending value. The loop's operation also depends onthe value of the loop's increment value, which enables you touse the loop control variable to count forward or backward byany given amount. As you'll see, <TT>for</TT> loops are used alot in Java programs. (In fact, they're a standard part of virtuallyall programming languages.) To be sure you understand <TT>for</TT>loops, look over the following questions and exercises.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>How do you kno<!-- 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 + -