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

📄 ch12.htm

📁 Java_by_Example,初级经典例子哦,珍藏版本
💻 HTM
📖 第 1 页 / 共 3 页
字号:
<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&nbsp;12</FONT></H1><H1><FONT SIZE=6 COLOR=#Ff0000>Functions</FONT></H1><HR><P><CENTER><B><FONT SIZE=5><A NAME="CONTENTS">CONTENTS</A></FONT></B></CENTER><UL><LI><A HREF="#TheTopDownApproachtoProgramming">The Top-Down Approach to Programming</A><LI><A HREF="#ExampleUsingFunctionsasSubroutines">Example: Using Functions as Subroutines</A><LI><A HREF="#DefiningandCallingFunctions">Defining and Calling Functions</A><LI><A HREF="#ExampleUsingFunctionstoReturnValues">Example: Using Functions to Return Values</A><LI><A HREF="#ExamplePuttingFunctionstoWork">Example: Putting Functions to Work</A><LI><A HREF="#Summary">Summary</A><LI><A HREF="#ReviewQuestions">Review Questions</A><LI><A HREF="#ReviewExercises">Review Exercises</A></UL><HR><P>Until now, your programs have been pretty short, each designedto demonstrate a single programming technique. When you startwriting real programs, however, you'll quickly discover that theycan grow to many pages of code. When programs get long, they alsoget harder to organize and read. To overcome this problem, professionalprogrammers break their programs down into individual functions,each of which completes a specific and well-defined task.<H2><A NAME="TheTopDownApproachtoProgramming"><FONT SIZE=5 COLOR=#Ff0000>The Top-Down Approach to Programming</FONT></A></H2><P>As I said, long programs are hard to organize and read. A full-lengthprogram contains many pages of code, and trying to find a specificpart of the program in all that code can be tough. You can usemodular program-design techniques to solve this problem. Usingmodular programming techniques, you can break a long program intoindividual modules, each of which performs a specific task.<P>In <A HREF="ch4.htm" >Chapter 4</A> &quot;Object-Oriented Programming Concepts,&quot;you got a quick look at modular program design, which is alsoknown as structured programming. In that chapter, I used the exampleof cleaning a house as a way to understand the process of breakingtasks up into specific steps. (The only reasonable way to cleanmy house is to douse it with gasoline and throw in a lighted match,but we won't get into that now.) You'll use that metaphor againhere, in preparation for learning about functions.<P>When cleaning a house, the main task might be called CLEAN HOUSE.Thinking about cleaning an entire house, however, can be overwhelming.So, to make the task easier, you can break it down into a numberof smaller steps. These steps might be CLEAN LIVING ROOM, CLEANBEDROOM, CLEAN KITCHEN, and CLEAN BATHROOM.<P>After breaking the housecleaning task down into room-by-room steps,you have a better idea of what to do. But cleaning a room is alsoa pretty big task-especially if it hasn't been done in a whileor if you have cats coughing up fur balls all over the place.So why not break each room step down, too? For example, cleaningthe living room could be broken down into PICK UP ROOM, DUST ANDPOLISH, CLEAN FURNITURE, and VACUUM RUG.<P>After breaking each room's cleaning down into steps, your housecleaningjob is organized much like a pyramid, with the general task onthe top. As you work your way down the pyramid, from the maintask to the room-by-room list and finally to the tasks for eachroom, the tasks get more and more specific.<P>Of course, when cleaning a house, you don't usually write a listof steps. If you're an efficient housecleaner, the steps are organizedin your mind. (If you clean house like I do, there are only twosteps: TURN ON TV and COLLAPSE ON COUCH.) However, when writinga program, which is a more conceptual task, you may not have aclear idea of exactly what needs to be done. This can lead toyour being overwhelmed by the project.<P>Breaking programming tasks down into steps, or modules, is calledmodular programming. And when you break your program's modulesdown into even smaller modules-as we did with the task of cleaninga house-you're using a top-down approach to program design. Byusing top-down programming techniques, you can write any programas a series of small, easy-to-handle tasks. In Java, the basicunit for organizing code in a top-down manner is the function.<H2><A NAME="ExampleUsingFunctionsasSubroutines"><FONT SIZE=5 COLOR=#Ff0000>Example: Using Functions as Subroutines</FONT></A></H2><P>When programmers talk about subroutines, they usually mean programmodules that return no value to your program. In a way, a subroutineis like a small program within your main program. If you writea housecleaning program, the subroutines in the main module mightbe called <TT>CleanLivingRoom()</TT>, <TT>CleanBedroom()</TT>,<TT>CleanKitchen()</TT>, and <TT>CleanBathroom()</TT>. The <TT>CleanLivingRoom()</TT>subroutine would contain all the steps needed to clean the livingroom, the <TT>CleanBedroom()</TT> subroutine would contain allthe steps needed to clean a bedroom, and so on.<P>Of course, it takes an extremely talented programmer to get acomputer to clean a house. (If you manage that trick, contactme immediately.) We need a more computer-oriented example. Supposeyou want to write a program that displays game instructions on-screen.Listing 12.1 shows one way you might accomplish this task in aJava applet. Figure 12.1 shows what the applet looks like.<P><A HREF="f12-1.gif"><B> Figure 12.1 : </B><I>This is the Applet13 applet running under Appletviewer.</I></A><P><HR><BLOCKQUOTE><B>Listing 12.1&nbsp;&nbsp;Applet13.java: Printing Instructionsin an Applet.<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>import java.awt.*;import java.applet.*;public class Applet13 extends Applet{    public void paint(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>Applet13 is about the simplest applet you can write. All it doesis display text. The text comprises instructions for playing asimple number game. If you had to sum up in a couple of wordsthe task performed by Applet13's <TT>paint()</TT> method, youmight come up with something like &quot;Draw Instructions,&quot;which is an excellent name for a function to handle that task.

⌨️ 快捷键说明

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