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

📄 ch9.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
statement. This time, the program compares the value of <TT>choice</TT>with the number 2. Because <TT>choice</TT> doesn't equal 2, theprogram ignores the following part of the statement and dropsdown to the next <TT>if</TT> statement. The variable <TT>choice</TT>doesn't equal 3 either, so the code portion of the third <TT>if</TT>statement is also ignored.<P>Suppose <TT>choice</TT> equals 2 when Java executes the code inListing 9.2. When the program gets to the first <TT>if</TT> statement,it discovers that <TT>choice</TT> is not equal to 1, so it ignoresthe <TT>num = 1</TT> statement and drops down to the next programline, which is the second <TT>if</TT> statement. Again, the programchecks the value of <TT>choice</TT>. Because <TT>choice</TT> equals2, the program can execute the second portion of the statement;that is, <TT>num</TT> gets set to 2. Program execution drops downto the third <TT>if</TT> statement, which does nothing because<TT>choice</TT> doesn't equal 3.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>The <TT>if</TT> statement, no matter how complex it becomes, always evaluates to either <TT>true</TT> or <TT>false</TT>. If the statement evaluates to <TT>true</TT>, the second portion of the statement is executed. If the statement evaluates to <TT>false</TT>, the second portion of the statement is not executed.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="MultipleLineIifIStatements">Multiple-Line <I>if</I> Statements</A></H3><P>Listings 9.1 and 9.2 demonstrate the simplest <TT>if</TT> statement.This simple statement usually fits your program's decision-makingneeds just fine. Sometimes, however, you want to perform morethan one command as part of an <TT>if</TT> statement. To performmore than one command, enclose the commands within curly braces.Listing 9.3 is a revised version of Listing 9.2 that uses thistechnique.<HR><BLOCKQUOTE><B>Listing 9.3&nbsp;&nbsp;LST9_3.LST: Multiple-Line </B><I>if</I><B>Statements.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>if (choice == 1){    num = 1;    num2 = 10;}if (choice == 2){    num = 2;    num2 = 20;}if (choice == 3){    num = 3;    num2 = 30;}</PRE></BLOCKQUOTE><HR><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>TIP</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Notice that some program lines in Listing 9.3 are indented. By indenting the lines that go with each <TT>if</TT> block, you can more easily see the structure of your program. Listing 9.3 also uses blank lines to separate blocks of code that go together. The compiler doesn't care about the indenting or the blank lines, but these features make your programs easier for you (or another programmer) to read.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>What's happening in Listing 9.3? Suppose <TT>choice</TT> equals2. When Java gets to the first <TT>if</TT> statement, it comparesthe value of <TT>choice</TT> with the number 1. Because thesevalues don't match (or, as programmers say, the statement doesn'tevaluate to <TT>true</TT>), Java skips over every line until itfinds the next <TT>if</TT> statement.<P>This brings Java to the second <TT>if</TT> statement. When Javaevaluates the expression, it finds that <TT>choice</TT> equals2, and it executes the second portion of the <TT>if</TT> statement.This time the second portion of the statement is not just onecommand, but two. The program sets the values of both <TT>num</TT>and <TT>num2</TT>.<P>This brings the program to the last <TT>if</TT> statement, whichJava skips over because <TT>choice</TT> doesn't equal 3. Noticethat, when you want to set up an <TT>if</TT> statement that executesmultiple lines of code, you must use the curly braces-<TT>{</TT>and <TT>}</TT>-to denote the block of instructions that shouldbe executed.<H3><A NAME="TheIelseIClause">The <I>else</I> Clause</A></H3><P>You might think it's a waste of time for Listing 9.3 to evaluateother <TT>if</TT> statements after it finds a match for the valueof <TT>choice</TT>. You'd be right, too. When you write programs,you should always look for ways to make them run faster; one wayto make a program run faster is to avoid all unnecessary processing.But how, you may ask, do you avoid unnecessary processing whenyou have to compare a variable with more than one value?<P>One way to keep processing to a minimum is to use Java's <TT>else</TT>clause. The <TT>else</TT> keyword enables you to use a single<TT>if</TT> statement to choose between two outcomes. When the<TT>if</TT> statement evaluates to <TT>true</TT>, the second partof the statement is executed. When the <TT>if</TT> statement evaluatesto <TT>false</TT>, the <TT>else</TT> portion is executed. (Whenthe <TT>if</TT> statement evaluates to neither <TT>true</TT> nor<TT>false</TT>, it's time to get a new computer!) Listing 9.4demonstrates how <TT>else</TT> works.<HR><BLOCKQUOTE><B>Listing 9.4&nbsp;&nbsp;LST9_4.LST: Using the </B><I>else</I><B>Clause.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>if (choice == 1){    num = 1;    num2 = 10;}else{    num = 2;    num2 = 20;}</PRE></BLOCKQUOTE><HR><P>In Listing 9.4, if <TT>choice</TT> equals 1, Java sets <TT>num</TT>to 1 and <TT>num2</TT> to 10. If <TT>choice</TT> is any othervalue, Java executes the <TT>else</TT> portion, setting <TT>num</TT>to 2 and <TT>num2</TT> to 20. As you can see, the <TT>else</TT>clause provides a default outcome for an <TT>if</TT> statement.A default outcome doesn't help much, however, if an <TT>if</TT>statement has to deal with more than two possible outcomes (asin the original Listing 9.3). Suppose you want to rewrite Listing9.3 so that it works the same but doesn't force Java to evaluateall three <TT>if</TT> statements unless it really has to. No problem.Listing 9.5 shows you how to use the <TT>else if</TT> clause:<HR><BLOCKQUOTE><B>Listing 9.5&nbsp;&nbsp;LST9_5.LST: Using </B><I>if</I><B> and</B><I>else</I><B> Efficiently.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>if (choice == 1){    num = 1;    num2 = 10;}else if (choice == 2){    num = 2;    num2 = 20;}else if (choice == 3){    num = 3;    num2 = 30;}</PRE></BLOCKQUOTE><HR><P>When Java executes the program code in Listing 9.5, if <TT>choice</TT>is 1, Java will look at only the first <TT>if</TT> section andskip over both of the <TT>else if</TT> clauses. That is, Javawill set <TT>num</TT> to 1 and <TT>num2</TT> to 10 and then continueon its way to whatever part of the program followed the final<TT>else if</TT> clause. Note that, if <TT>choice</TT> doesn'tequal 1, 2, or 3, Java must evaluate all three clauses in thelisting but will not do anything with <TT>num</TT> or <TT>num2</TT>.<H3><A NAME="ExampleUsingtheIifIStatementinaProgram">Example: Using the <I>if</I> Statement in a Program</A></H3><P>Now that you've studied what an <TT>if</TT> statement looks likeand how it works, you probably want to see it at work in a realprogram. Listing 9.6 is a Java program that uses the menu exampleyou studied earlier in this chapter, whereas Listing 9.7 is theHTML document that runs the applet. Figure 9.1 shows the appletrunning in the Appletviewer application.<P><A HREF="f9-1.gif"><B> Figure 9.1 : </B><I>The Applet6 applet enables you to choose colors.</I></A><P><HR><BLOCKQUOTE><B>Listing 9.6&nbsp;&nbsp;Applet6.java: Using an </B><I>if</I><B>Statement in a Program.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet6 extends Applet{    TextField textField1;    public void init()    {        textField1 = new TextField(5);        add(textField1);g.drawString(&quot;3. Green&quot;, 40, 115);        String s = textField1.getText();        int choice = Integer.parseInt(s);        if (choice == 1)            g.setColor(Color.red);        else if (choice == 2)            g.setColor(Color.blue);        else if (choice == 3)            g.setColor(Color.green);        else            g.setColor(Color.black);        if ((choice &gt;= 1) &amp;&amp; (choice &lt;= 3))            g.drawString(&quot;This is the color you chose.&quot;, 60, 140);        else            g.drawString(&quot;Invalid menu selection.&quot;, 60, 140);    }    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>Applet6</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&quot;1&quot;.<BR>    Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR>        Display user instructions in the applet's display area.<BR>        Display the color menu on three lines.<BR>        Get the text from the <TT>TextField</TT> object.<BR>        Convert the text to an integer.<BR>        Select a color based on the value the user entered.<BR>        Display a message in the appropriate color.<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 9.7&nbsp;&nbsp;APPLET6.htmL: The HTML Document ThatRuns Applet6.<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;Applet6.class&quot;    width=250    height=150    name=&quot;Applet6&quot;&gt;&lt;/applet&gt;</PRE></BLOCKQUOTE><HR><P>If you were awake at all during <A HREF="ch7.htm" >Chapter 7</A> you should alreadyknow how most of the Applet6 applet works. But, there's some newstuff in the <TT>paint()</TT> method that warrants a close look.First, after converting the user's typed selection from text toan integer, the program uses the integer in an <TT>if</TT> statementto match up each menu selection with the appropriate color. The<TT>setColor()</TT> method is part of the <TT>Graphics</TT> object;you call it to set the color of graphical elements, such as text,that the program draws in the applet's display area. The <TT>setColor()</TT>method's single argument is the color to set. As you can see,Java has a <TT>Color</TT> object that you can use to select colors.You'll learn more about the <TT>Color</TT> object in <A HREF="ch36.htm" >Chapter 36</A>,&quot;The Java Class Libraries.&quot; Notice that, if the user'sselection does not match a menu selection, the color is set toblack.<P>After the program sets the color, a second <TT>if</TT> statementdetermines which text to display, based on whether the user entereda valid selection. If the user's selection is valid, the programdisplays &quot;This is the color you chose.&quot; in the selectedcolor. Otherwise, the program displays &quot;Invalid menu selection&quot;in black.<H2><A NAME="TheIswitchIStatement"><FONT SIZE=5 COLOR=#Ff0000>The <I>switch</I> Statement</FONT></A></H2><P>Another way you can add decision-making code to your programsis with the <TT>switch</TT> statement. The <TT>switch</TT> statementgets its name from the fact that it enables a computer programto switch between different outcomes based on a given value. Thetruth is, a <TT>switch</TT> statement does much the same job asan <TT>if</TT> statement, but it is more appropriate for situationswhere you have many choices, rather than only a few. Look at the<TT>if</TT> statement in Listing 9.8:<HR><BLOCKQUOTE><B>Listing 9.8&nbsp;&nbsp;LST9_8.TXT: A Typical </B><I>if</I><B>Statement.<BR></B></BLOCKQUOTE>

⌨️ 快捷键说明

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