📄 ch7.htm
字号:
<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 7</FONT></H1><H1><FONT SIZE=6 COLOR=#Ff0000>Math Operators</FONT></H1><HR><P><CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER><UL><LI><A HREF="#TheAdditionOperator">The Addition Operator</A><UL><LI><A HREF="#ExampleUsingtheAdditionOperator">Example: Using the Addition Operator</A><LI><A HREF="#ExampleMultipleAdditions">Example: Multiple Additions</A></UL><LI><A HREF="#TheSubtractionOperator">The Subtraction Operator</A><UL><LI><A HREF="#ExampleUsingtheSubtractionOperator">Example: Using the Subtraction Operator</A><LI><A HREF="#ExampleMultipleSubtractionsUsingMixedDataTypes">Example: Multiple Subtractions Using Mixed Data Types</A><LI><A HREF="#ExampleCastingaResulttoaDifferentDataType">Example: Casting a Result to a Different Data Type</A></UL><LI><A HREF="#TheMultiplicationOperator">The Multiplication Operator</A><UL><LI><A HREF="#ExampleMultiplicationandDataTypes">Example: Multiplication and Data Types</A></UL><LI><A HREF="#TheDivisionOperator">The Division Operator</A><UL><LI><A HREF="#ExampleIntegerVersusFloatingPointDivision">Example: Integer Versus Floating-Point Division</A></UL><LI><A HREF="#TheModuloOperator">The Modulo Operator</A><LI><A HREF="#TheIncrementOperator">The Increment Operator</A><LI><A HREF="#TheDecrementOperator">The Decrement Operator</A><LI><A HREF="#ExampleUsingMathematicalCalculationsinanApplet">Example: Using Mathematical Calculations in an Applet</A><UL><LI><A HREF="#HowAppletWorks">How Applet5 Works</A></UL><LI><A HREF="#TheOrderofOperations">The Order of Operations</A><UL><LI><A HREF="#ExampleOrderofOperations">Example: Order of Operations</A><LI><A HREF="#ExampleMoreOrderofOperations">Example: More Order of Operations</A><LI><A HREF="#ExampleStillMoreOrderofOperations">Example: Still More Order of Operations</A><LI><A HREF="#ExampleOneLastOrderofOperations">Example: One Last Order of Operations</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 <A HREF="ch5.htm" >Chapter 5</A> "Constants and Variables," you got a quicklook at a few math operators, including the times (*), plus (+),and minus (-) signs. You even got a chance to use these operatorsin a few simple mathematical formulas. There's still a lot moreto learn about math operators, though, as you'll discover as youread this chapter. Here, you'll not only learn a few more operators,but also learn about operator precedence, which determines theorder in which operations are performed.<H2><A NAME="TheAdditionOperator"><FONT SIZE=5 COLOR=#Ff0000>The Addition Operator</FONT></A></H2><P>In case you were sleeping during second grade, you might liketo know that the addition operator (+) is used to compute thesum of two values. As with all mathematical operations, Java performsthese summing tasks just as you did in your second-grade homework.For example, the following line shows the general form of an additionoperation in Java:<BLOCKQUOTE><PRE>result = expr1 + expr2;</PRE></BLOCKQUOTE><P>Here, the values represented by <TT>expr1</TT> and <TT>expr2</TT>are added together (summed), with the result being assigned tothe variable represented by <TT>result</TT>. The values <TT>expr1</TT>and <TT>expr2</TT> are actually expressions, which means thatthey can be anything from a literal number like 5 to a complexformula like 5*(3+7)^10. You'll get a closer look at expressionsin the next chapter, "Expressions."<H3><A NAME="ExampleUsingtheAdditionOperator">Example: Using the Addition Operator</A></H3><P>Suppose you want to sum the values of two variables. For example,you're writing a program that asks the user for two values andthen prints the sum of the values. Assuming that the user's valuesget stored in two variables called <TT>value1</TT> and <TT>value2</TT>,you might write a line of Java code that looks like this:<BLOCKQUOTE><PRE>sum = value1 + value2;</PRE></BLOCKQUOTE><P>In this example, if the user entered 12 as the value for <TT>value1</TT>and 15 as the value for <TT>value2</TT>, after Java executed theline, <TT>sum</TT> would be equal to 27.<H3><A NAME="ExampleMultipleAdditions">Example: Multiple Additions</A></H3><P>In the previous example, you saw the simplest way you can usethe addition operator. However, you are not limited to addingonly two values. You can, in fact, add as many expressions asyou like. To extend the previous example, suppose you have fourvalues you need to sum. You can use a line of code like this:<BLOCKQUOTE><PRE>sum = value1 + value2 + value3 + value4;</PRE></BLOCKQUOTE><P>As you'll see in <A HREF="ch8.htm" >Chapter 8</A> "Expressions," you can createall kinds of complicated mathematical formulas with Java.<H2><A NAME="TheSubtractionOperator"><FONT SIZE=5 COLOR=#Ff0000>The Subtraction Operator</FONT></A></H2><P>You can use the subtraction operator, which looks like a minussign (-), to subtract one value or expression from another. Althoughthe subtraction operator yields a different result than the additionoperator (thank heavens for that), it's used in exactly the sameway, as you can see by this general example:<BLOCKQUOTE><PRE>result = expr1 - expr2;</PRE></BLOCKQUOTE><P>Here, the value represented by <TT>expr2</TT> is subtracted from<TT>expr1</TT>, with the result being assigned to the variable<TT>result</TT>. Just as you learned with the addition operator,the values <TT>expr1</TT> and <TT>expr2</TT> are expressions thatcan be anything that results in a numerical value.<H3><A NAME="ExampleUsingtheSubtractionOperator">Example: Using the Subtraction Operator</A></H3><P>Suppose you want to subtract the value of one variable from another.For example, the program you're writing requires that you subtracta customer's monthly payment from the balance he owes. You mightwrite a line of Java code that looks like this:<BLOCKQUOTE><PRE>new_balance = current_balance - payment;</PRE></BLOCKQUOTE><P>In this example, if the customer's current balance was $110 andhe paid $25, after Java executed the line, <TT>new_balance</TT>would be equal to $85. (Of course, the subtraction is being donewith the numbers 110 and 25, and the result is 85. The computerdoesn't know anything about dollars, a fact that makes it toughfor a computer to do its grocery shopping.)<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Although the examples you've seen so far use integers, you can use mathematical operators with any type of numerical value, including floating-point.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H3><A NAME="ExampleMultipleSubtractionsUsingMixedDataTypes">Example: Multiple Subtractions Using Mixed Data Types</A></H3><P>You know from your experience with the addition operator thatyou can use more than one mathematical operator in a calculation.The same is true with the subtraction operator. You can also usedifferent types of values in the calculation. For example, supposeyou needed to subtract both an integer and a floating-point valuefrom another integer. You could perform this task with a calculationlike this:<BLOCKQUOTE><PRE>difference = 100 - 15 - 3.5f;</PRE></BLOCKQUOTE><P>After Java executes the above line, the variable <TT>difference</TT>will be equal to 81.5. But do you see a potential problem? Whattype of value is 81.5? If you said "floating point,"go to the head of the class. Because 81.5 is a floating-pointvalue, <TT>difference</TT> must be a floating-point variable.If <TT>difference</TT> is an integer, Java's compiler will generatean error that tells you "Explicit cast needed to convertfloat to int." What Java is really saying here is, "Ifyou want to have an integer result, you've got to tell me."In the next example, you see how to tell Java this important information.<H3><A NAME="ExampleCastingaResulttoaDifferentDataType">Example: Casting a Result to a Different Data Type</A></H3><P>When you cast a value, you're telling Java that it's okay to convertone type of value to another. You do this by placing in frontof the calculation, in parentheses, the data type you want. Forexample, look at this line of Java code:<BLOCKQUOTE><PRE>difference = 100 - 15 - 3.5f;</PRE></BLOCKQUOTE><P>Because the calculation on the right side of the equals sign resultsin a floating-point number, <TT>difference</TT> must be a floating-pointvariable. After all, computers are very fussy. They refuse todo things like try to stuff a floating-point number into an integer.If <TT>difference</TT> is an integer, then the result of the calculationmust also be an integer. In the above case, you can satisfy Java'scompiler by using a type cast, which looks like this:<BLOCKQUOTE><PRE>difference = (int)(100 - 15 - 3.5f);</PRE></BLOCKQUOTE><P>Now, when Java executes the above line, it first calculates theresult of <TT>100-15-3.5</TT>f, which is 81.5. Then, it convertsthe result to an integer by dropping the decimal portion of thevalue. This gives a result of 81. Finally, Java assigns the valueof 81 to <TT>difference</TT>, which is an integer variable. Inshort, when you use a type cast, you're telling the compiler,"Yes, I know what I'm doing. I want the result converted."<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Sometimes the minus sign is used as a negation operator, rather than a subtraction operator. For example, if you want to write a negative number, like negative ten, you'd use the negation operator like this: -10. This is a case where the same symbol is used to mean different things. Java can tell the difference between the negation and a subtraction operators by the context in which the operator is used.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="TheMultiplicationOperator"><FONT SIZE=5 COLOR=#Ff0000>The Multiplication Operator</FONT></A></H2><P>By now, you should be getting used to using mathematical operationsin simple expressions. The multiplication operator (*) is no differentfrom the addition and subtraction operators, except that it performsa different type of operation. When you want to multiply two numberstogether, you use the multiplication operator like this:<BLOCKQUOTE><PRE>result = expr1 * expr2;</PRE></BLOCKQUOTE><P>After Java executes this line, <TT>result</TT> contains the productof <TT>expr1</TT> times <TT>expr2</TT>. The most important thingto remember about multiplication is that you can run into somepretty big numbers fast. If the result of a multiplication is
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -