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

📄 ch7.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
larger than the data type of the variable that'll hold the answer,you've got trouble, as you'll see in the following example.<H3><A NAME="ExampleMultiplicationandDataTypes">Example: Multiplication and Data Types</A></H3><P>Try to determine the result of the following calculation:<BLOCKQUOTE><PRE>byte product = (byte)(20 * 20);</PRE></BLOCKQUOTE><P>If you said the answer is 400, you'd be both right and wrong.While it is true that 20 times 20 is 400, <TT>product</TT> isonly a <TT>byte</TT> variable, which means it can only hold valuesfrom -128 to 127. Unfortunately, Java just goes ahead and stuffsthe answer into <TT>product</TT> whether it fits or not. (The<TT>byte</TT> type-cast, in fact, converts the answer to a bytebefore it's stuffed into <TT>product</TT>, but that's a minorcomplication.) In the preceding case, you'd end up with an answerof -112.<P>Be especially careful when you're performing more than one multiplicationin a calculation. In such cases, numbers can really get out ofhand if you're using the smaller data types like <TT>byte</TT>or <TT>short</TT>. Most Java programmers use the <TT>int</TT>data type for their integer variables, which ensures that theirvariables have plenty of room for large numbers.<P>Of course, as I've said before, you should choose the smallestdata type that is large enough for the values you'll be using,since the computer must work harder, and thus slower, when ituses larger data types. Still, if you're not performing tons ofcalculations, using larger data types for safety sake probablywon't make a noticeable change in the speed of your applet.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>TIP</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>When a mathematical calculation gives you an answer that seems way out of whack, check to make sure that you're using data types that are large enough to hold the values used in the calculation. This is especially true for the result of the calculation. Many hard-to-find program bugs result from using the wrong data types for large values.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="TheDivisionOperator"><FONT SIZE=5 COLOR=#Ff0000>The Division Operator</FONT></A></H2><P>As you may have guessed, the next operator on the list is thedivision operator (/), which enables you to divide one value byanother. The division operator is used exactly like the otheroperators you've studied so far, as you can see by this line:<BLOCKQUOTE><PRE>result = expr1 / expr2;</PRE></BLOCKQUOTE><P>Here, <TT>result</TT> ends up as the result of <TT>expr1</TT>divided by <TT>expr2</TT>. As with multiplication, there's a traplurking here, but this time it doesn't have as much to do withthe size of the numbers as it does in the division operation itself.The problem is that almost all division calculations end up withfloating-point values as answers. The following example demonstratesthis potential problem.<H3><A NAME="ExampleIntegerVersusFloatingPointDivision">Example: Integer Versus Floating-Point Division</A></H3><P>Look at this calculation:<BLOCKQUOTE><PRE>int result = 3 / 2;</PRE></BLOCKQUOTE><P>When you divide 3 by 2, you may start out with integers, but youend up with 1.5 for an answer, and 1.5 is, of course, a floating-pointnumber. But when Java performs the division shown above, it performsinteger division. That is, it drops any decimal portion in theanswer, leaving <TT>result</TT> equal to 1. There are times whenthis is the type of division you want to perform. But if you wantthe precise answer to <TT>3 / 2</TT>, you're going to have tochange something. Maybe changing <TT>result</TT> to a floating-pointvariable will make a difference:<BLOCKQUOTE><PRE>float result = 3 / 2;</PRE></BLOCKQUOTE><P>When Java performs this calculation, you still end up with 1 asthe answer. Why? Because, as I mentioned before, Java performsinteger division on integer values like 3 and 2. To solve theproblem, you must also convert 3 and 2 to floating-point values,like this:<BLOCKQUOTE><PRE>float result = 3f / 2f;</PRE></BLOCKQUOTE><P>Now, you'll get the correct result of 1.5. Actually, only oneof the numbers to the right of the equals sign needs to be floating-pointin order to get a floating-point answer. This line will work,too:<BLOCKQUOTE><PRE>float result = 3f / 2;</PRE></BLOCKQUOTE><H2><A NAME="TheModuloOperator"><FONT SIZE=5 COLOR=#Ff0000>The Modulo Operator</FONT></A></H2><P>In the previous section, you learned that integer division givesyou a result that's equal to the number of times one number fitsinto another, regardless of the remainder. For example, you nowknow that, in Java, the answer to &quot;3 divided by 2&quot; is1, meaning that 2 fits into 3 only once. Integer division throwsaway the remainder, but what if it's the remainder you're lookingfor? Then, you can use the modulo operator (%) like this:<BLOCKQUOTE><PRE>result = expr1 % expr2;</PRE></BLOCKQUOTE><P>This line results in the remainder of <TT>expr1</TT> divided by<TT>expr2</TT>. For example, the calculation<BLOCKQUOTE><PRE>int result = 11 % 3;</PRE></BLOCKQUOTE><P>makes <TT>result</TT> equal to 2, because 3 goes into 11 threetimes with a remainder of 2. You probably won't use the modulooperator much, but it can be handy for special types of calculations.<H2><A NAME="TheIncrementOperator"><FONT SIZE=5 COLOR=#Ff0000>The Increment Operator</FONT></A></H2><P>Many times in a program, you want to increase a value by a specificamount. For example, if you were using the variable <TT>count</TT>to keep track of how many times a part of your program executed,you need to add 1 to <TT>count</TT> each time you reached thatpart of the program. Programmers used to do this kind of incrementinglike this:<BLOCKQUOTE><PRE>count = count + 1;</PRE></BLOCKQUOTE><P>Here, the computer takes the value stored in <TT>count</TT>, increasesit by 1, and then assigns the new value to <TT>count</TT>. Ifyou've ever programmed in C or C++, you know that those languageshave a shortcut way of incrementing a value. Because Java is muchlike C++, its creators also included this shortcut operator. Usingthe increment operator (++), you can replace the previous linewith this one:<BLOCKQUOTE><PRE>++count;</PRE></BLOCKQUOTE><P>Another way to write the preceding line is like this:<BLOCKQUOTE><PRE>count++;</PRE></BLOCKQUOTE><P>There is, however, a subtle difference in the way the incrementoperator works when it's placed before (pre-increment) or after(post-increment) the value it's incrementing. The difference cropsup when you use the operator in expressions. For example, lookat these lines of Java program code:<BLOCKQUOTE><PRE>int num1 = 1;int num2 = ++num1;</PRE></BLOCKQUOTE><P>Here, Java first sets the variable <TT>num1</TT> to 1. In thesecond line, Java increments <TT>num1</TT> to 2 and then assigns2 to <TT>num2</TT>.<P>Now, look at these lines:<BLOCKQUOTE><PRE>int num1 = 1;int num2 = num1++;</PRE></BLOCKQUOTE><P>This time, <TT>num2</TT> ends up as 1. Why? In the second line,Java doesn't increment <TT>num1</TT> until after it assigns thecurrent value of <TT>num1</TT> (1) to <TT>num2</TT>. Watch outfor this little detail when you get started writing your own applets.<P>What if you want to increment a value by more than 1? The old-fashionedway would be to use a line like this:<BLOCKQUOTE><PRE>num = num + 5;</PRE></BLOCKQUOTE><P>Java has a special shortcut operator that handles the above situation,too. You use the shortcut operator like this:<BLOCKQUOTE><PRE>num += 5;</PRE></BLOCKQUOTE><P>The above line just says, &quot;Add 5 to <TT>num</TT>.&quot;<H2><A NAME="TheDecrementOperator"><FONT SIZE=5 COLOR=#Ff0000>The Decrement Operator</FONT></A></H2><P>In computer programs, you don't always count forwards. Often,you need to count backwards as well. That's why Java has the decrementoperator (- -), which works just like the increment operator,except it subtracts 1 instead of adding it. You use the decrementoperator like this:<BLOCKQUOTE><PRE>-&nbsp;-num;</PRE></BLOCKQUOTE><P>The above example uses the pre-decrement version of the operator.If you want to decrement the value after it's been used in anexpression, use the post-decrement version, like this:<BLOCKQUOTE><PRE>num-&nbsp;-;</PRE></BLOCKQUOTE><P>The set of operators wouldn't be complete without a decrementoperator that enables you to subtract any value from a variable.The following line<BLOCKQUOTE><PRE>num -= 5;</PRE></BLOCKQUOTE><P>tells Java to decrement <TT>num</TT> by 5.<H2><A NAME="ExampleUsingMathematicalCalculationsinanApplet"><FONT SIZE=5 COLOR=#Ff0000>Example: Using Mathematical Calculations in an Applet</FONT></A></H2><P>It's one thing to learn about mathematical operators and how they'reused to perform calculations. It's quite another to actually usethese operators in an actual program. This is because, when performingcalculations in programs, you frequently have to do a lot of conversionsfrom numerical values to strings and vice versa. For example,suppose you ask the user for a number that you need in order toperform a calculation. When you retrieve the number from the user,it's still in string form. You can't use the text character &quot;3&quot;in a calculation. You need to convert the string form of &quot;3&quot;to the numerical form.<P>Once you have all your values converted to the right form, youcan go ahead and do the calculations as you learned in this chapter.But what about when you want to show the answers to your applet'suser? Again, you need to perform a conversion, this time fromnumerical form back to string form. Listing 7.1 shows an appletcalled Applet5 that demonstrates how these conversion tasks work.Figure 7.1 shows Applet5 running in the Appletviewer application.<P><A HREF="f7-1.gif"><B> Figure 7.1 : </B><I>The Applet5 applet sums two values. </I></A><P><HR><BLOCKQUOTE><B>Listing 7.1&nbsp;&nbsp;Applet5.java: Source Code for the Applet5Applet.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet5 extends Applet{    TextField textField1;    TextField textField2;    public void init()    {        textField1 = new TextField(5);        textField2 = new TextField(5);        add(textField1);        add(textField2);        textField1.setText(&quot;0&quot;);        textField2.setText(&quot;0&quot;);    }    public void paint(Graphics g){        int value1;        int value2;        int sum;        g.drawString(&quot;Type a number in each box.&quot;, 40, 50);        g.drawString(&quot;The sum of the values is:&quot;, 40, 75);        String s = textField1.getText();        value1 = Integer.parseInt(s);        s = textField2.getText();        value2 = Integer.parseInt(s);        sum = value1 + value2;        s = String.valueOf(sum);        g.drawString(s, 80, 100);    }    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>Applet5</TT> class from Java's <TT>Applet</TT>class.<BR>     Declare <TT>TextField</TT> objects called <TT>textField1</TT>and <TT>textField2</TT>.<BR>    Override the<TT> Applet </TT>class's<TT> init() </TT>method.<BR>        Create the two <TT>TextField</TT> objects.<BR>        Add the two <TT>TextField</TT> objects to the applet.<BR>        Initialize the text in both <TT>TextField</TT> objectsto &quot;0&quot;.<BR>    Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR>        Declare three integers called <TT>value1,value2,</TT>and <TT>sum</TT>.<BR>        Display two text strings in the applet's display area.<BR>        Get the text from first <TT>TextField</TT> object.<BR>        Convert the text to an integer.<BR>        Get the text from the second <TT>TextField</TT> object.<BR>        Convert the text to an integer.<BR>        Add the two converted values together.<BR><TT>        </TT>Convert the sum to a string.<BR>        Draw the text string on the applet's surface.<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><P>Use the procedures you learned in the previous chapter to compileand run the Applet5 applet. Remember that to do this, you mustfollow these steps:<OL><LI>Type and save the program (or copy it from the CD-ROM).

⌨️ 快捷键说明

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