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

📄 ch7.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<LI>Compile the applet.<LI>Write an HTML document to test the applet.<LI>Use Appletviewer to display the HTML document containing theapplet.</OL><P>When you have the Applet5 applet up and running, enter a numberinto each text box, and then press Enter. When you do, the appletsums the two numbers and displays the result.<H3><A NAME="HowAppletWorks">How Applet5 Works</A></H3><P>Although Applet5's source code is a little longer than other appletsyou've seen, it's really not much more complicated. It simplyuses a few more variables in order to store the values neededto perform its calculations.<P>First, near the top of the program, Applet5 declares two <TT>TextField</TT>objects, like this:<BLOCKQUOTE><PRE>TextField textField1;TextField textField2;</PRE></BLOCKQUOTE><P>These <TT>TextField</TT> objects represent the text boxes in whichthe user types the values to be summed.<P>Next, the program overrides the Applet class's <TT>init()</TT>method. In this method, it first creates two new <TT>TextField</TT>objects:<BLOCKQUOTE><PRE>textField1 = new TextField(5);textField2 = new TextField(5);</PRE></BLOCKQUOTE><P>The program then adds the <TT>TextField</TT> objects to the applet:<BLOCKQUOTE><PRE>add(textField1);add(textField2);</PRE></BLOCKQUOTE><P>Finally, in order to be sure the program doesn't try to sum twonon-existent values, <TT>init()</TT> initializes the text containedin the <TT>TextField</TT> objects to &quot;0&quot;:<BLOCKQUOTE><PRE>textField1.setText(&quot;0&quot;);textField2.setText(&quot;0&quot;);</PRE></BLOCKQUOTE><P>The <TT>TextField</TT> class's <TT>setText()</TT> method setsthe text contained in the control to the text string given asthe method's single argument.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Overriding a method is the process of replacing a method found in the base class with a version specific to the new class. In other words, the Applet class from which Applet5 is derived also has an <TT>init()</TT> method. If you didn't override <TT>init()</TT> in Applet5, Java would call the original version in Applet instead. (See the example called &quot;Encapsulation, Inheritance, and Polymorphism&quot; in <A HREF="ch4.htm" >Chapter 4</A>for more information.)</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The <TT>paint() </TT>method is where all the action takes place.In <TT>paint()</TT>, the program first declares three integervariables:<BLOCKQUOTE><PRE>int value1;int value2;int sum;<BR></PRE></BLOCKQUOTE><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Because it takes a certain amount of time for a computer to allocate memory for variables, it's not always a good idea to declare variables inside the <TT>paint()</TT> method, which must run as quickly as possible. I chose to use this generally frowned upon practice in order to keep the programming examples simple and easy-to-understand. However, keep in mind that the <TT>paint()</TT> method must do as little processing as possible in order to keep it up to speed.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>After declaring its variables, <TT>paint()</TT> displays two linesof text on the applet's display area:<BLOCKQUOTE><PRE>g.drawString(&quot;Type a number in each box.&quot;, 40, 50);g.drawString(&quot;The sum of the values is:&quot;, 40, 75);</PRE></BLOCKQUOTE><P>Then, the program extracts the text from the first <TT>TextField</TT>object and converts that text from a string to a numerical value(in this case, an integer):<BLOCKQUOTE><PRE>String s = textField1.getText();value1 = Integer.parseInt(s);</PRE></BLOCKQUOTE><P>You've seen the <TT>TextField</TT> class's <TT>getText()</TT>method before. The second line above, however, introduces youto a new class and method. The <TT>Integer</TT> class offers manymethods that make working with integers easier. For example, the<TT>parseInt()</TT> method used in the second line above enablesyou to convert the contents of a string to an integer (assuming,of course, that the string contains numerical digits).<P>After converting the first string to an integer, <TT>paint()</TT>handles the second <TT>TextField</TT> object in exactly the sameway:<BLOCKQUOTE><PRE>s = textField2.getText();value2 = Integer.parseInt(s);</PRE></BLOCKQUOTE><P>Now the program has two integer values, stored in the variables<TT>value1</TT> and <TT>value2</TT>, that it can sum, which itdoes like this:<BLOCKQUOTE><PRE>sum = value1 + value2;</PRE></BLOCKQUOTE><P>After Java executes the above lines, the answer to the calculationis stored in <TT>sum</TT>. The program now needs to display theanswer to the applet's user. However, before it can do that, itmust convert the numerical value in <TT>sum</TT> to a text stringthat can be displayed on the screen. You know that the <TT>String</TT>class's <TT>valueOf()</TT> method handles this task. The lastthing <TT>paint()</TT> does, then, is convert <TT>sum</TT> toa string and display the string on the screen:<BLOCKQUOTE><PRE>s = String.valueOf(sum);g.drawString(s, 80, 100);</PRE></BLOCKQUOTE><P>The last method in Applet3 is <TT>action()</TT>, which you learnedabout in the previous chapter. To review, Java calls <TT>action()</TT>whenever the user performs some action with the applet's controls.In this case, <TT>action()</TT> responds when the user pressesEnter in one of the <TT>TextField</TT> objects.<H2><A NAME="TheOrderofOperations"><FONT SIZE=5 COLOR=#Ff0000>The Order of Operations</FONT></A></H2><P>Now that you know how to use mathematical operators, you needto know about the complications you can run into when you usedifferent operators in the same calculation. The order of operations,which is also called operator precedence, determines the orderin which mathematical computations are performed. If you've evertaken algebra, you know that mathematicians long ago set up astandard set of symbols for mathematical operations as well asdefined the order in which they're performed. These mathematicalrules are also observed in programming languages like Java. Table7.1 lists Java's mathematical operators in order of precedence.<BR><P><CENTER><B>Table 7.1&nbsp;&nbsp;Operator Order of Operations.</B></CENTER><P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD WIDTH=157><CENTER><I><B>Operator</B></I></CENTER></TD><TD WIDTH=186><I><B>Description</B></I></TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>-</CENTER></TD><TD WIDTH=186>Negation</TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>++</CENTER></TD><TD WIDTH=186>Increment</TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>-&nbsp;-</CENTER></TD><TD WIDTH=186>Decrement</TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>*</CENTER></TD><TD WIDTH=186>Multiplication</TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>/</CENTER></TD><TD WIDTH=186>Division</TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>%</CENTER></TD><TD WIDTH=186>Modulus</TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>+</CENTER></TD><TD WIDTH=186>Addition</TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>-</CENTER></TD><TD WIDTH=186>Subtraction</TD></TR><TR VALIGN=TOP><TD WIDTH=157><CENTER>=</CENTER></TD><TD WIDTH=186>Assignment</TD></TR></TABLE></CENTER><P><P>As I mentioned previously, operator precedence comes into playwhen you use several different operators in the same calculation.For example, look at this line of Java source code:<BLOCKQUOTE><PRE>answer = 3 + 5 * 3;</PRE></BLOCKQUOTE><P>Go ahead and do the calculation. What did you get for an answer?If you got 18, you already know how operator precedence works.If you're new to this sort of thing, you probably got 24 for ananswer, which is incorrect. The reason 18 is the correct answeris because operator precedence dictates that the multiplicationbe performed before the addition. If you look at Table 7.1, youcan see that multiplication comes before addition.<P>If you really wanted to get 24 for an answer, you could use parenthesesto change the order of operations, like this:<BLOCKQUOTE><PRE>answer = (3 + 5) * 3;</PRE></BLOCKQUOTE><P>Now, the answer would be 24, because the parentheses tell Javato do the addition first.<H3><A NAME="ExampleOrderofOperations">Example: Order of Operations</A></H3><P>If you've never dealt with order of operations before, you'llprobably need a little practice to get the hang of it. Look atthis calculation:<BLOCKQUOTE><PRE>answer = 5 + 3 - 2 + 7;</PRE></BLOCKQUOTE><P>You should get 13 for an answer. Because addition and subtractionhave the same order of precedence in this calculation (yes, Iknow the table lists subtraction after addition, but if you dothe subtraction first, you'll still get 13 for an answer), youcan just work from left to right to solve this problem.<H3><A NAME="ExampleMoreOrderofOperations">Example: More Order of Operations</A></H3><P>The previous example was pretty easy. Ready to try something alittle tougher? Look at this calculation:<BLOCKQUOTE><PRE>answer = 4 * 5 + 4 / 2;</PRE></BLOCKQUOTE><P>What do you get for an answer? You should have gotten 22. If yougot 12, you forgot that multiplication and division are performedbefore addition.<H3><A NAME="ExampleStillMoreOrderofOperations">Example: Still More Order of Operations</A></H3><P>Suppose I change the previous example to this:<BLOCKQUOTE><PRE>answer = 4 * (5 + 4) / 2;</PRE></BLOCKQUOTE><P>You should get 18 for an answer, because the added parenthesestell you to perform the addition first.<H3><A NAME="ExampleOneLastOrderofOperations">Example: One Last Order of Operations</A></H3><P>Okay, now you're going to get a chance to prove that you reallyknow your stuff. Solve this calculation:<BLOCKQUOTE><PRE>answer = 2 * 3 + 6 * 3 - (4 + 2) * 2;</PRE></BLOCKQUOTE><P>The answer is 12. You solve the problem as shown below:<BLOCKQUOTE>answer = 2 * 3 + 6 * 3 - (4 + 2) * 2;<BR>answer = 2 * 3 + 6 * 3 - 6 * 2;<BR>answer = 6 + 6 * 3 - 6 * 2;<BR>answer = 6 + 18 - 6 * 2;<BR>answer = 6 + 18 - 12;<BR>answer = 12;</BLOCKQUOTE><H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Almost all computer programs perform mathematical calculations.So that you can specify the types of calculations you want performed,computer languages such as Java feature mathematical operatorsfor standard operations such as addition, subtraction, multiplication,and division. However, when using these operators, always rememberoperator precedence (or order of operations), which determinesthe order in which calculations are completed.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What symbols does Java use for the addition, subtraction,multiplication, and division operators?<LI>What does <TT>5*3</TT> equal?<LI>What is the answer to <TT>3 - 2 + 5 + 6 - 1</TT>?<LI>If <TT>num</TT> equals 12, what does the expression <TT>++num</TT>do?<LI>What result do you get from <TT>12 % 5</TT>?<LI>If <TT>num</TT> equals 25, what does the expression <TT>num+= 5</TT> do?<LI>How do you set the text in a <TT>TextField</TT> object?<LI>What is the answer to <TT>12 + 3 * 6 / 2</TT>?<LI>How do you change the calculation <TT>3 / 5</TT> so that isuses floating-point division?<LI>How do you use casting to change the result of <TT>56 - 34.56f</TT>from floating point to integer?<LI>How do you convert digits in a string to an integer value?<LI>What is the answer to <TT>(12 - 8) * 10 / 2 * 2</TT>?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>On a piece of paper, write an expression that sums five numbers.<LI>Write an expression that uses both addition and multiplicationwith four numbers.<LI>Use parentheses to change the order of operations in the expressionyou wrote in the previous exercise.<LI>Modify Applet5 so that it accepts three values from the user.Divide the second value by the third and then add the first value.Rename the program <TT>MathApplet.java</TT>. Figure 7.2 showswhat the final applet should look like. (You can find the solutionto this programming problem in the CHAP07 folder of this book'sCD-ROM.)<BR><A HREF="f7-2.gif"><B> Figure 7.2 : </B><I>MathApplet should look like this.</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 + -