📄 ch12.htm
字号:
guesses = 0; number = CreateNumber(); } public void paint(Graphics g) { DrawInstructions(g); int guess = GetGuess(); ShowMessage(g, guess); } public boolean action(Event event, Object arg) { ++guesses; repaint(); return true; } //////////////////////////////////////// // Private methods. //////////////////////////////////////// void DrawInstructions(Graphics g) { g.drawString("Try to guess the number I am", 48, 65); g.drawString("thinking of. The number will be", 48, 80); g.drawString("between 0 and 100. You have an", 48, 95); g.drawString("unlimited number of tries.", 48, 110); g.drawString("Good Luck.", 95, 140); } int GetGuess() { String s = textField1.getText(); int num = Integer.parseInt(s); return num; } int CreateNumber() { float n = (float)Math.random(); number = (int)(n * 100 + 1); return number; } void ShowMessage(Graphics g, int guess) { String s = "Guesses so far: "; s += String.valueOf(guesses); g.drawString(s, 80, 170); if (guess < number) g.drawString("Your guess is too low.", 70, 185); else if (guess > number) g.drawString("Your guess is too high.", 70, 185); else g.drawString("You guessed the number!", 65, 185); }}</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>Tell Java that the program uses the lang package's <TT>Math</TT>class.<BR>Derive the <TT>Applet15</TT> class from Java's <TT>Applet</TT>class.<BR> Declare the class's data fields.<BR> Override the <TT>Applet</TT> class's <TT>init()</TT> method.<BR> Create the <TT>TextField</TT> object.<BR> Add the <TT>TextField</TT> object to the applet.<BR> Initialize the text in the <TT>TextField</TT> object to"50."<BR> Initialize the guess counter to zero.<BR> Create the number that the player must guess.<BR> Override the <TT>Applet</TT> class's <TT>paint()</TT> method.<BR> Print the game's instructions.<BR> Get the player's guess.<BR> Show the appropriate message based on the guess.<BR> Override the <TT>Applet</TT> class's <TT>action()</TT> method.<BR> Increment the guess counter.<BR> Tell Java to redraw the applet's display area.<BR> Tell Java that the <TT>action()</TT> method finished successfully.<BR> Define the private <TT>DrawInstructions()</TT> method.<BR> Display the game instructions in the applet.<BR> Define the private <TT>GetGuess()</TT> method.<BR> Get the text from the <TT>TextField</TT> object.<BR> Convert the text to an integer.<BR> Return the integer to the calling function.<BR> Define the private <TT>CreateNumber() </TT>method.<BR> Calculate a random number from 0 to 1.<BR> Convert the random number to an integer between 1 and100.<BR> Return the random number to the calling function.<BR> Define the private <TT>ShowMessage() </TT>method.<BR> Display the number of guesses so far.<BR> Display the results of the player's latest guess.</BLOCKQUOTE><HR><BLOCKQUOTE><B>Listing 12.6 APPLET15.htmL: Applet15's HTML Document.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE><title>Applet Test Page</title><h1>Applet Test Page</h1><applet code="Applet15.class" width=250 height=250 name="Applet15"></applet></PRE></BLOCKQUOTE><HR><P>When you run Applet15, the program selects a random numeral from1 to 100. Your task is to guess the numeral in the least numberof tries. You type your guesses into the box at the top of theapplet. When the program starts, this box contains the number50, and the hint at the bottom of the screen tells you whetherthe number is high or low. Each time you enter a new number, thehint tells you whether the guess is high or low.<P>Yes, it's true that Applet15 is much larger than the example appletsyou've used so far in this book, but the program needs to be longin order to accommodate several different functions. By analyzingthe program's flow, you can determine whether or not you understandhow functions work.<P>Start with the <TT>paint()</TT> method. By examining the functioncalls it contains, you can get a good idea of what the programdoes. Specifically, the program displays the game's instructions,gets a guess from the user, and then displays a message to theuser. If you were only interested in examining the <TT>paint()</TT>method, you wouldn't have to go any further; the details of howthese other functions work are tucked out of your way.<P>If you wanted to see exactly how the program prints the game'sinstructions, however, you could find the <TT>DrawInstructions()</TT>method in the source code. The same is true for the other functionscalled in the <TT>paint()</TT> method.<P>You can see that some of the functions return values and othersdon't. Similarly, some functions require arguments and othersdon't. How the function is constructed depends on whether it mustcalculate and return a value to the program (such as in <TT>CreateNumber()</TT>)and whether the function requires values from the program in orderto perform its task (such as <TT>ShowMessage()</TT>, which needsthe <TT>Graphics</TT> object and the player's latest guess).<P>There are probably several lines of Java source code in Listing12.5 that don't make sense to you right now. The pseudocode sectionfollowing the listing describes, in general, what the programis doing. You'll learn about many of the details in other chapters.At this point, you only need to worry about being able to followthe function calls.<H2><A NAME="Summary"><FONT SIZE=5 COLOR=#Ff0000>Summary</FONT></A></H2><P>Functions enable you to break complicated programs down into easy-to-handlechunks. Moreover, by using a top-down structure, your programscan organize code with functions that start off being generalin nature but get more detailed as you work your way deeper intothe hierarchy. When a function doesn't return a value (has a returntype of <TT>void</TT>), it is used as a subroutine, which simplyperforms some task before program execution jumps back to theline after the line that called the function. A function witha return type other than <TT>void</TT> enables your programs tocalculate a value and return the value to the calling function.Either type of function can have one or more arguments, whichenable the program to pass values into the function.<H2><A NAME="ReviewQuestions"><FONT SIZE=5 COLOR=#Ff0000>Review Questions</FONT></A></H2><OL><LI>What is top-down programming?<LI>How do functions make top-down programming possible?<LI>Do all functions return values?<LI>What are arguments and how are they used?<LI>What is meant by "defining a function"?<LI>How do you return a value from a function?<LI>How do the arguments given in a function call relate to thearguments accepted by the function?<LI>How do you determine how to break a program up into functions?</OL><H2><A NAME="ReviewExercises"><FONT SIZE=5 COLOR=#Ff0000>Review Exercises</FONT></A></H2><OL><LI>Write a function that prints a two-line message to the user.<LI>Write a function that returns the number 1 as an integer.<LI>Write a function that accepts two integer arguments and returnsthe sum of the arguments.<LI>Modify the function from exercise 3 so that it sums the twoarguments, calls yet another function that multiplies the twoarguments, sums the product and the original sum, and returnsthe result. Write the function that performs the multiplication.<LI>Modify Applet15 by adding a function that starts the gameover each time the user guesses the number. That is, after theuser guesses the number, the program should select a new randomnumber and continue the game. Name the program <TT>GuessApplet.java</TT>.(You can find the solution to this programming problem in theCHAP12 folder of this book's CD-ROM.)</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 + -