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

📄 ch9.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<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;9</FONT></H1><H1><FONT SIZE=6 COLOR=#Ff0000>The <I>if</I> and <I>switch</I>Statements</FONT></H1><HR><P><CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER><UL><LI><A HREF="#ControllingProgramFlow">Controlling Program Flow</A><LI><A HREF="#ProgramFlowandBranching">Program Flow and Branching</A><LI><A HREF="#TheIifIstatement">The <I>if</I> statement</A><UL><LI><A HREF="#ExampleTheFormofanIifIStatement">Example: The Form of an <I>if</I> Statement</A><LI><A HREF="#MultipleIifIStatements">Multiple <I>if</I> Statements</A><LI><A HREF="#MultipleLineIifIStatements">Multiple-Line <I>if</I> Statements</A><LI><A HREF="#TheIelseIClause">The <I>else</I> Clause</A><LI><A HREF="#ExampleUsingtheIifIStatementinaProgram">Example: Using the <I>if</I> Statement in a Program</A></UL><LI><A HREF="#TheIswitchIStatement">The <I>switch</I> Statement</A><UL><LI><A HREF="#ExampleUsingtheIbreakIStatementCorrectly">Example: Using the <I>break</I> Statement Correctly</A><LI><A HREF="#ExampleUsingtheIswitchIStatementinaProgram">Example: Using the <I>switch</I> Statement in a Program</A></UL><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>In previous chapters, you've learned a lot about the way Javaworks. You now know how to type and compile programs, how to inputand output simple data, how to perform mathematical operations,and how to perform comparisons using logical expressions. Butthese techniques are merely the building blocks of a program.To use these building blocks in a useful way, you have to understandhow computers make decisions.<P>In this chapter, you learn how your programs can analyze datain order to decide what parts of your program to execute. Untilnow, your applets have executed their statements in strict sequentialorder, starting with the first line of a method and working, lineby line, to the end of the method. Now it's time to learn howyou can control your program flow-the order in which the statementsare executed-so that you can do different things based on thedata your program receives.<H2><A NAME="ControllingProgramFlow"><FONT SIZE=5 COLOR=#Ff0000>Controlling Program Flow</FONT></A></H2><P>Program flow is the order in which a program executes its statements.Most program flow is sequential, meaning that the statements areexecuted one by one in the order in which they appear in the programor method. However, there are Java commands that make your programjump forward or backward, skipping over program code not currentlyrequired. These commands are said to control the program flow.<P>If the idea of computers making decisions based on data seemsa little strange, think about how you make decisions. For example,suppose you're expecting an important letter. You go out to yourmailbox and look inside. Based on what you find, you choose oneof two actions:<UL><LI>If there's mail in the mailbox, you take the mail into thehouse.<LI>If there's no mail in the mailbox, you complain about thepostal system.</UL><P>In either case, you've made a decision based on whether thereis mail in the mailbox. This is called conditional branching.<P>Computers use this same method to make decisions (except theynever complain and they don't give a darn how late your mail is).You will see the word <TT>if</TT> used frequently in computerprograms. Just as you might say to yourself, &quot;If the mailis in the mailbox, I'll bring it in,&quot; a computer also usesan <TT>if</TT> statement to decide what action to take.<H2><A NAME="ProgramFlowandBranching"><FONT SIZE=5 COLOR=#Ff0000>Program Flow and Branching</FONT></A></H2><P>Most programs reach a point where a decision must be made abouta piece of data. The program must then analyze the data, decidewhat to do about it, and jump to the appropriate section of code.This decision-making process is as important to computer programmingas pollen is to a bee. Virtually no useful programs can be writtenwithout it.<P>When a program breaks the sequential flow and jumps to a new sectionof code, it is called branching. When this branching is basedon a decision, the program is performing conditional branching.When no decision-making is involved and the program always brancheswhen it encounters a branching instruction, the program is performingunconditional branching. Unconditional branching is rarely usedin modern programs, so this chapter deals with conditional branching.<H2><A NAME="TheIifIstatement"><FONT SIZE=5 COLOR=#Ff0000>The <I>if</I> statement</FONT></A></H2><P>Most conditional branching occurs when the program executes an<TT>if</TT> statement, which compares data and decides what todo next based on the result of the comparison. For example, you'veprobably seen programs that print menus on-screen. To select amenu item, you often type the item's selection number. When theprogram receives your input, it checks the number you enteredand decides what to do. You'd probably use an <TT>if</TT> statementin this type of program.<P>A simple <TT>if</TT> statement includes the keyword <TT>if</TT>followed by a logical expression, which, as you learned in theprevious chapter, is an expression that evaluates to either <TT>true</TT>or <TT>false</TT>. These expressions are surrounded by parentheses.You follow the parentheses with the statement that you want executedif the logical expression is true. For example, look at this <TT>if</TT>statement:<BLOCKQUOTE><PRE>if (choice == 5)    g.drawString(&quot;You chose number 5.&quot;, 30, 30);</PRE></BLOCKQUOTE><P>In this case, if the variable <TT>choice</TT> is equal to 5, Javawill execute the call to <TT>drawString()</TT>. Otherwise, Javawill just skip the call to <TT>drawString()</TT>.<H3><A NAME="ExampleTheFormofanIifIStatement">Example: The Form of an <I>if</I> Statement</A></H3><P>The syntax of languages such as Java are tolerant of the stylesof various programmers, enabling programmers to construct programsthat are organized in a way that's best suited to the programmerand the particular problem. For example, the Java language isnot particular about how you specify the part of an <TT>if</TT>statement to be executed. For example, the statement<BLOCKQUOTE><PRE>if (choice == 1)    num = 10;</PRE></BLOCKQUOTE><P>could also be written like this:<BLOCKQUOTE><PRE>if (choice == 1) num = 10;</PRE></BLOCKQUOTE><P>In other words, although the parentheses are required around thelogical expression, the code to be executed can be on the sameline or the line after the <TT>if</TT> statement.<P>In the case of an <TT>if</TT> statement that contains only oneprogram line to be executed, you can choose to include or do awaywith the curly braces that usually mark a block of code. Withthis option in mind, you could rewrite the preceding <TT>if</TT>statement like Listing 9.1.<HR><BLOCKQUOTE><B>Listing 9.1&nbsp;&nbsp;LST9_1.TXT: The <I>if</I> Statementwith Braces.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>if (choice == 1){    num = 10;}</PRE></BLOCKQUOTE><HR><P>Another way you'll often see braces used with an <TT>if</TT> statementis shown here:<BLOCKQUOTE><PRE>if (choice == 1) {    num = 10;}</PRE></BLOCKQUOTE><P>In this case, the opening brace is on the <TT>if</TT> statement'sfirst line.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Logical expressions are also called <I>Boolean </I>expressions. That is, a Boolean expression is also an expression that evaluates to either <TT>true</TT> or <TT>false</TT>. Now you understand why Java has a <TT>boolean</TT> data type, which can hold the value <TT>true</TT> or <TT>false</TT>. Having the <TT>boolean</TT> data type enables you to assign the result of a logical expression to a variable.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="MultipleIifIStatements">Multiple <I>if</I> Statements</A></H3><P>You can use a number of <TT>if</TT> statements to choose betweenseveral conditions. For example, look at the group of <TT>if</TT>statements in Listing 9.2.<HR><BLOCKQUOTE><B>Listing 9.2&nbsp;&nbsp;LST9_2.TXT: A Group of </B><I>if</I><B>Statements.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>if (choice == 1)    num = 1;if (choice == 2)    num = 2;if (choice == 3)    num = 3;</PRE></BLOCKQUOTE><HR><P>How do these <TT>if</TT> statements work? Let's say that whenJava executes the program code in Listing 9.2, the variable <TT>choice</TT>equals 1. When the program gets to the first <TT>if</TT> statement,it checks the value of <TT>choice</TT>. If <TT>choice</TT> equals1 (which it does, in this case), the program sets the variable<TT>num</TT> to 1 and then drops down to the next <TT>if</TT>

⌨️ 快捷键说明

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