📄 ch9.htm
字号:
<BLOCKQUOTE><PRE>if (x == 1) y = 1;if (x == 2) y = 2;if (x == 3) y = 3;else y = 0;</PRE></BLOCKQUOTE><HR><P>You could easily rewrite the preceding <TT>if </TT>statement asa <TT>switch</TT> statement, as shown in Listing 9.9:<HR><BLOCKQUOTE><B>Listing 9.9 LST9_9.TXT: Changing an </B><I>if</I><B>to a </B><I>switch<B>.<BR></B></I></BLOCKQUOTE><BLOCKQUOTE><PRE>switch(x){ case 1: y = 1; break; case 2: y = 2; break; case 3: y = 3; break; default: y = 0;}</PRE></BLOCKQUOTE><HR><P>The first line of a <TT>switch</TT> statement is the keyword <TT>switch</TT>followed by the variable whose value will determine the outcome.This variable is called the control variable. Inside the main<TT>switch</TT> statement (which begins and ends with curly braces)are a number of <TT>case</TT> clauses, one for each possible valueof the <TT>switch</TT> control variable (the <TT>x</TT>, in thiscase). In the above example, if <TT>x</TT> equals 1, Java jumpsto the <TT>case 1</TT> and sets <TT>y</TT> equal to 1. Then, the<TT>break</TT> statement tells Java that it should skip over therest of the <TT>switch</TT> statement.<P>If <TT>x</TT> is 2, the same sort of program flow occurs, exceptJava jumps to the <TT>case 2</TT>, sets <TT>y</TT> equal to 2,and then breaks out of the <TT>switch</TT>. If the <TT>switch</TT>control variable is not equal to any of the values specified bythe various <TT>case</TT> clauses, Java jumps to the <TT>default</TT>clause. The <TT>default</TT> clause, however, is optional. Youcan leave it out if you want, in which case Java will do nothingif there's no matching <TT>case</TT> for the control variable.<H3><A NAME="ExampleUsingtheIbreakIStatementCorrectly">Example: Using the <I>break</I> Statement Correctly</A></H3><P>One tricky thing about <TT>switch</TT> statements is the variousways that you can use the <TT>break</TT> statement to controlprogram flow. Look at Listing 9.10:<HR><BLOCKQUOTE><B>Listing 9.10 LST9_10.TXT: Using </B><I>break</I><B>to Control Program Flow.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>switch(x){ case 1: y = 1; case 2: y = 2; break; case 3: y = 3; break; default: y = 0;}</PRE></BLOCKQUOTE><HR><P>In this example, funny things happen, depending on whether thecontrol variable <TT>x</TT> equals 1 or 2. In the former case,Java first jumps to <TT>case 1</TT> and sets <TT>y</TT> equalto 1. Then, because there is no <TT>break</TT> before the <TT>case2</TT> clause, Java continues executing statements, dropping throughthe <TT>case 2</TT> and setting <TT>y</TT> equal to 2. Ouch! Themoral of the story is: Make sure you have <TT>break</TT> statementsin the right places.<P>If the outcome of Listing 9.10 was really what you wanted to happen,you'd probably rewrite the <TT>switch</TT> statement is to looklike Listing 9.11:<HR><BLOCKQUOTE><B>Listing 9.11 LST9_11.TXT: Rewriting Listing 9.10.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>switch(x){ case 1: case 2: y = 2; break; case 3: y = 3; break; default: y = 0;}</PRE></BLOCKQUOTE><HR><P>Here, just as in Listing 9.10, <TT>y</TT> will end up equal to2 if <TT>x</TT> equals 1 or 2. You'll run into this type of <TT>switch</TT>statement a lot in Java programs. If you're a C or C++ programmer,you've already seen a lot of this sort of thing, so you shouldfeel right at home.<H3><A NAME="ExampleUsingtheIswitchIStatementinaProgram">Example: Using the <I>switch</I> Statement in a Program</A></H3><P>You've seen that a <TT>switch</TT> statement is similar in manyways to an <TT>if</TT> statement. In fact, <TT>if</TT> and <TT>switch</TT>statements can easily be converted from one to the other. Listing9.12 is a new version of Applet6 (called Applet7) that incorporatesthe menu example by using a <TT>switch</TT> statement insteadof an <TT>if</TT> statement.<HR><BLOCKQUOTE><B>Listing 9.12 APPLET7.JAVA: Using a </B><I>switch</I><B>Statement in a Program.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet7 extends Applet{ TextField textField1; public void init() { textField1 = new TextField(5); add(textField1); textField1.setText("1"); } public void paint(Graphics g) { g.drawString("Type a menu choice in the above box.", 20, 50); g.drawString("1. Red", 40, 75); g.drawString("2. Blue", 40, 95); g.drawString("3. Green", 40, 115); String s = textField1.getText(); int choice = Integer.parseInt(s); switch(choice) { case 1: g.setColor(Color.red); break; case 2: g.setColor(Color.blue); break; case 3: g.setColor(Color.green); break; default: g.setColor(Color.black); } if ((choice >= 1) && (choice <= 3)) g.drawString("This is the color you chose.", 60, 140); else g.drawString("Invalid menu selection.", 60, 140); } public boolean action(Event event, Object arg) { repaint(); return true; }}</PRE></BLOCKQUOTE><HR><P>When you run this program, you'll see the same display as theone you saw with Applet6. In fact, from the user's point of view,the program works exactly the same as the previous version. Thedifferences are completely internal.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Making decisions based on the state of data is an important partof a computer program, and now that you have this chapter behindyou, you've made a giant leap forward in your Java programmingcareer. You now have enough Java programming savvy to write simple,yet useful, applets. Of course, that's not to say that there isn'ta lot left to learn. But by now you should have a good idea ofwhat a Java applet looks like and how it works. The remainderof this book will fill out the details that make Java appletsso powerful.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What is program flow?<LI>Define conditional and unconditional branching.<LI>What are two ways to control program flow?<LI>In the following Java example, if <TT>num</TT> equals 5, willthe second line execute?<BR><TT>if (choice == 3)<BR><FONT FACE="Courier New"> num2 = choice;</FONT></TT><LI>Are there times when you don't need braces with an <TT>if</TT>statement? Explain.<LI>What's the difference between a logical expression and a Booleanexpression?<LI>In Listing 9.13, what happens when <TT>choice</TT> equals5?<LI>Compare and contrast the <TT>if </TT>and <TT>switch</TT> statements.<LI>What value is assigned to <TT>num</TT> in Listing 9.14 when<TT>choice</TT> equals 2?</OL><HR><BLOCKQUOTE><B>Listing 9.13 LST9_13.LST: Listing for Question 7.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>if (choice == 1){ num = 1; num2 = 10;}else if (choice == 2){ num = 2; num2 = 20;}</PRE></BLOCKQUOTE><HR><HR><BLOCKQUOTE><B>Listing 9.14 LST9_14.TXT: Listing for Question 10.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>switch(choice){ case 1: num = 1; break; case 2: num = 2; case 3: num = 3; break; default: num = 0;}</PRE></BLOCKQUOTE><HR><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write an <TT>if</TT> statement that sets the variable <TT>num</TT>to 1 when <TT>choice</TT> equals 10.<LI>Write an <TT>if</TT> statement that sets the variable <TT>num</TT>to the same value as the control variable <TT>choice</TT> when<TT>choice</TT> equals 5, but sets <TT>num</TT> to 0 in everyother case.<LI>Write an <TT>if</TT> statement that sets the variable <TT>num</TT>to twice the value of the control variable <TT>choice</TT>. Validvalues for <TT>choice</TT> are 3, 4, 5, and 6.<LI>Convert the <TT>if</TT> statement in exercise 3 to a <TT>switch</TT>statement.<LI>Modify Applet7 so that it displays the text string "One,""Two," "Three," or "Four" when theuser enters 1, 2, 3, or 4, respectively. Have the program display"Invalid value" for any other user entry. Figure 9.2shows what the final applet, called SwitchApplet, should looklike. (You can find the solution to this programming problem inthe CHAP09 folder of this book's CD-ROM.)<BR><A HREF="f9-2.gif"><B> Figure 9.2 : </B><I>The SwitchApplet applet converts numbers to words.</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 + -