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

📄 ch12.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
Listing 12.2 is a new version of the applet that isolates theinstruction-display task in its own function. When you run thisapplet, it looks identical to Applet13.<HR><BLOCKQUOTE><B>Listing 12.2&nbsp;&nbsp;Applet14.java: Placing the Instructionsin a Function.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet14 extends Applet{    public void paint(Graphics g)    {        DrawInstructions(g);    }    void DrawInstructions(Graphics g)    {        g.drawString(&quot;Try to guess the number I am&quot;, 48, 65);        g.drawString(&quot;thinking of. The number will be&quot;, 48, 80);        g.drawString(&quot;between 0 and 100. You have an&quot;, 48, 95);        g.drawString(&quot;unlimited number of tries.&quot;, 48, 110);        g.drawString(&quot;Good Luck.&quot;, 95, 140);    }}</PRE></BLOCKQUOTE><HR><P>Now for the million-dollar question: How does this Applet14 work?The program is divided into two functions. The first is the <TT>paint()</TT>method, which Java calls whenever the applet's display area mustbe redrawn. In this applet, <TT>paint()</TT> is at the highestlevel of your top-down design. That is, no other part of the programcalls <TT>paint()</TT>, but <TT>paint()</TT> calls functions thatare lower in level.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>You might be confused about the difference between methods, functions, and subroutines. The truth is that they are very similar. Specifically, a method is a function that is part of a class. So, in Applet14, both <TT>paint()</TT> and <TT>DrawInstructions()</TT> are methods of the <TT>Applet14</TT> class. (They are also functions.) A subroutine is a function that returns no value. That is, it has the word <TT>void</TT> in front of its name.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><P>The second function in Listing 12.2 is the <TT>DrawInstructions()</TT>subroutine, which is really just a Java function that returnsno value to the calling function (<TT>paint()</TT>, in this case).<TT>DrawInstructions()</TT> is one level down from the main programin the top-down design. In <TT>paint()</TT>, instead of havingall the code that's needed to display the instructions, you onlyhave a line that calls the function that handles this task. Thismakes it easier to see what's going on in <TT>paint()</TT>. Ifyou need to see more detail, you can always drop down a levelin your program and take a look at <TT>DrawInstructions()</TT>.<H2><A NAME="DefiningandCallingFunctions"><FONT SIZE=5 COLOR=#Ff0000>Defining and Calling Functions</FONT></A></H2><P>There are two things you must do to use a function in a program.The first thing you must do is define the function, which meansthat you must write all the program instructions that make upthe function, placing the instructions between curly braces. Youmust also determine what arguments the function must have in orderto perform its task. In Applet14, the <TT>DrawInstructions()</TT>function definition looks like Listing 12.3.<HR><BLOCKQUOTE><B>Listing 12.3&nbsp;&nbsp;LST12_3.TXT: The DrawInstructions(&nbsp;)Subroutine.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>void DrawInstructions(Graphics g){    g.drawString(&quot;Try to guess the number I am&quot;, 48, 65);    g.drawString(&quot;thinking of. The number will be&quot;, 48, 80);    g.drawString(&quot;between 0 and 100. You have an&quot;, 48, 95);    g.drawString(&quot;unlimited number of tries.&quot;, 48, 110);    g.drawString(&quot;Good Luck.&quot;, 95, 140);}</PRE></BLOCKQUOTE><HR><P>The first line of Listing 12.3 tells Java the type of value returnedfrom the function, the name of the function, and the argumentsthat must be sent to the function when it's called. In this case,the type of return value is <TT>void</TT>, which means the functionreturns no value. The name of the function is <TT>DrawInstructions</TT>,and its argument is a <TT>Graphics</TT> object called <TT>g</TT>.(Notice that, in the function's first line, you must list boththe argument type and argument name.) If you look at the <TT>paint()</TT>method, you can see that Applet14 calls the <TT>DrawInstructions()</TT>function like this:<BLOCKQUOTE><PRE>DrawInstructions(g);</PRE></BLOCKQUOTE><P>This line tells Java that you want to execute the program codein the <TT>DrawInstructions()</TT> function and that you wantto pass the <TT>Graphics</TT> object <TT>g</TT> to the function.<TT>DrawInstructions()</TT> needs access to <TT>g</TT> becauseit is the <TT>Graphics</TT> object that has the <TT>drawString()</TT>method. Without access to the <TT>Graphics</TT> object, <TT>DrawInstructions()</TT>cannot perform its task in the same way that the <TT>drawString()</TT>method cannot display a string unless you give it the string andthe location at which to display the string.<P>The second thing you must do to use a function is to call thefunction. When you call a function, program execution jumps tothe commands that make up the function. All commands in the functionare executed, after which the program returns to the line afterthe function call.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>The arguments you place between the parentheses of a function call must be of the same type and in the same order as the arguments given in the function's first line. That is, the call <TT>DrawInstructions(g)</TT> and the first line of the function, <TT>DrawInstructions(Graphics g)</TT>, match perfectly because the function call sends a <TT>Graphics</TT> object and the function expects a <TT>Graphics</TT> object. The names of the arguments, however, don't have to match. For example, the function call <TT>DrawInstructions(g)</TT> and the function name <TT>DrawInstructions(Graphics graph)</TT> are still a match. The only difference is that you'd have to refer to <TT>graph</TT> inside the <TT>DrawInstructions()</TT> function, rather than to <TT>g</TT>.</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="ExampleUsingFunctionstoReturnValues"><FONT SIZE=5 COLOR=#Ff0000>Example: Using Functions to Return Values</FONT></A></H2><P>In Java, functions are the main way you can break up your programsinto modules. But unlike when you used functions as subroutines,some types of functions return a value to the main program. You'veused this type of Java function before in this book. The <TT>String</TT>class' <TT>valueOf()</TT> method is one. The value it returnsis the numerical value of a string containing digits.<P>You can assign a function's return value to a variable. Supposeyou have a function named <TT>GetNum()</TT> that calculates anumber and returns it to your program. A call to the functionmight look something like this:<BLOCKQUOTE><PRE>int num = GetNum();</PRE></BLOCKQUOTE><P>The function might look something like Listing 12.4.<HR><BLOCKQUOTE><B>Listing 12.4&nbsp;&nbsp;LST12_4.TXT: An Example of a Function.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>int GetNum(){    ++value;    return value;}</PRE></BLOCKQUOTE><HR><P>Listing 12.4 shows some of the differences between using functionsas subroutines (which return no value) and using functions toreturn values. While functions being used as subroutines alwaysstart with the keyword <TT>void</TT>, functions that return valuesstart with the keyword <TT>int</TT>, <TT>char</TT>, <TT>float</TT>or whatever type of return value you need. Also, since subroutinesreturn no value, they need no <TT>return</TT> statement. But asyou can see, the <TT>GetNum()</TT> function returns a value byusing the <TT>return</TT> keyword along with the value to be returned.If you fail to include the <TT>return</TT> command in the bodyof a function that returns a value, Java's compiler will giveyou an error message.<P><CENTER><TABLE BORDER=1 WIDTH=80%><TR VALIGN=TOP><TD><B>NOTE</B></TD></TR><TR VALIGN=TOP><TD><BLOCKQUOTE>Normally, arguments passed into a function are <I>passed by value</I>, which means that a copy of the passed value is given to the function. When you change the value of the argument in the function, you are changing the copy, while the original value stays the same. However, some arguments are <I>passed by reference</I>, which means that the original object is passed to the function. In this case, changing the argument's value in the function changes the original value, too. You learn about passing by reference in <A HREF="ch13.htm" >Chapter 13</A>, &quot;Arrays.&quot;</BLOCKQUOTE></TD></TR></TABLE></CENTER><P><H2><A NAME="ExamplePuttingFunctionstoWork"><FONT SIZE=5 COLOR=#Ff0000>Example: Putting Functions to Work</FONT></A></H2><P>Think you understand functions now? The applet you'll build inthis example will put your knowledge to the test. Listing 12.5is the applet's source code, whereas Listing 12.6 is the HTMLdocument that'll load and run the applet. Figure 12.2 shows whatthe applet looks like when it's running under Appletviewer.<P><A HREF="f12-2.gif"><B> Figure 12.2 : </B><I>This is the Applet15 applet running under Appletviewer.</I></A><P><HR><BLOCKQUOTE><B>Listing 12.5&nbsp;&nbsp;APPLET15.JAVA: Using Functions in aJava Applet.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;import java.lang.Math;public class Applet15 extends Applet{    ///////////////////////////////////////    // Data fields.    ///////////////////////////////////////    TextField textField1;    int guesses;    int number;    ////////////////////////////////////////    // Overridden methods.    ////////////////////////////////////////    public void init()    {        textField1 = new TextField(10);        add(textField1);        textField1.setText(&quot;50&quot;);

⌨️ 快捷键说明

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