




已阅读5页,还剩4页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
0外文原文IntroductiontoJavaApplicationsJavaprogramsconsistofpiecescalledclasses.YoucanprogrameachpieceyoumayneedtofromaJavaprogram.However,mostJavaprogrammerstakeadvantageofrichcollectionsofexistingclassesinjavalibraries.Thus,therearereallytwopiecestolearningthejava“world”,thefirstislearningthejavalanguageitselfsothatyoucanprogramyourownclasses;thesecondishowtousetheclassesintheextensivejavaclasslibraries.TheJavalanguagefacilitatesadisciplinedapproachtocomputerprogramdesign.WenowintroduceJavaprogrammingandpresentexamplesthatillustrateseveralimportantfeaturesofJava.Eachexampleisanalyzedonelineatatime.WepresentadetailedtreatmentofprogramdevelopmentandprogramcontrolinJava.Javausesnotationsthatmayappearstrangetononprogrammers.Webeginbyconsideringasimpleapplicationthatdisplayedalineoftext.Anapplicationisaprogramthatexecutesusingthejavainterpreter(discussedlaterinthissection).ThisprogramillustratesseveralimportantfeaturesoftheJavalanguage.Weconsidereachlineoftheprogramindetail.Eachprogramwepresentinthisbookhaslinenumbersincludedforthereadersconvenience;linenumbersarenotpartofactualJavaprograms.Line9doesthe“realword”oftheprogram,namelydisplayingthephraseWelcometoJavaProgramming!Butletusconsidereachlineinorder.Line1,Beginswith/,indicatingthattheremainderofthelineisacomment.Programmersinsertcommentstodocumentprogramsandimproveprogramreadability.Commentsalsohelpotherpeoplereadandunderstandaprogram.Commentsdonotcausethecomputertoperformanyactionwhentheprogramisrun.TheJavacompilerignorescomments.Webegineveryprogramwithacommentindicatingthefigurenumberandfilename(line1).1/Welcome1.java2/AfirstprograminJava.3publicclassWelcome14/mainmethodbeginsexecutionofJavaapplication15publicstaticvoidmain(Stringargs)67System.out.println(“WelcometoJavaProgramming!”);89/endmethodmain0knowallofthedetailsofafeatureinorderforyoutousethatfeatureinJava.Allprogrammersinitiallylearnhowtoprogrambymimickingwhatotherprogrammershavedonebeforethem.Foreachdetailweaskyoutomimic,weindicatewherethefulldiscussionwillbepresentedlaterinthetext.Whenyousaveyourpublicclassdefinitioninafile,thefilenamemustbetheclassnamefollowedbythe“.java”file-nameextension.ForourapplicationthefilenameisWelcome1.java.AllJavaclassdefinitionsarestoredinfilesendingwiththefile-nameextension”java.”Itisanerrorforapublicclassifthefilenameisnotidenticaltotheclassname(plusthe.javaextension)intermsofbothspellingandcapitalization.Therefore,itisalsoanerrorforafiletocontaintwoormorepublicclasses.Itisanerrornottoendafilenamewiththe.javaextensionforafilecontaininganapplicationsclassdefinition.Iftheextensionismissing,theJavacompilerwillnotbeabletocompiletheclassdefinition.Aleftbrace(attheendofline4),beginthebodyofeveryclassdefinition.Acorrespondingrightbrace(inline13inthisprogram),mustendeachclassdefinition.Noticethatlines6-11areindented.Thisindentationisoneofthespacingconventionsmentionedearlier.WedefineeachspacingconventionasagoodprogrammingPractice.Wheneveryoutypeanopeningleftbrace,inyourprogram,immediatelytypetheclosingrightbrace,thenrepositionthecursorbetweenthebracestobegintypingthebody.Thispracticehelpspreventerrorsduetomissingbraces.Indenttheentirebodyofeachclassdefinitionone“level”ofindentationbetweenthe2leftbrace,andtherightbrace,thatdefinethebodyoftheclass.Thisformatemphasizesthestructureoftheclassdefinitionandhelpsmaketheclassdefinitioneasiertoread.Setaconventionfortheindentsizeyouprefer,andthenuniformlyapplythatconvention.TheTabkeymaybeusedtocreateindents,buttabstopsmayvarybetweeneditors.Werecommendusingthreespacestoformalevelofindent.Ifbracesdonotoccurinmatchingpairs,thecompilerindicatesanerror.Line5isablankline,insertedforprogramreadability.Line6,/mainmethodbeginsexecutionofJavaapplicationLine7,Publicstaticvoidmain(Stringargs)Javaapplicationsbeginexecutingatmain.AftermainindicatethatmainisaprogrambuildingblockcalledamethodJavaclassdefinitionsnormallycontainoneormoremethods.ForaJavaapplicationclass,exactlyoneofthosemethodsmustbecalledmainandmustbedefinedasshownonline7;otherwise,thejavainterpreterwillnotexecutetheapplication.Methodsareabletoperformtasksandreturninformationwhentheycompletetheirtasks.Thevoidkeywordindicatesthatthismethodwillperformatask(displayingalineoftext,inthisprogram),butwillnotreturnanyinformationwhenitcompletesitstask.Later,wewillseethatmanymethodsreturninformationwhentheycompletetheirtask.Methodsareexplainedindetail.Fornow,simplymimicmainsfirstlineinyourJavaapplications.Indenttheentirebodyofeachmethoddefinitionone“level”ofindentationbetweentheleft,andtherightbrace,thatdefinethebodyofthemethod.Thisformatmakesthestructureofthemethodstandoutandhelpsmakethemethoddefinitioneasiertoread.Line9,System.out.println(“WelcometoJavaProgramming!”);Instructsthecomputertoperformanaction,namelytoprintthestringofcharacterscontainedbetweenthedoublequotationmarks.Astringissometimescalledacharacterstring,amessageorastringliteral.Werefertocharactersbetweendoublequotationmarksgenericallyasstrings.White-spacecharactersinstringsarenotignoredbythecompiler.3System.outisknownasthestandardoutputobject.System.outallowsJavaapplicationstodisplaystringsandothertypesofinformationinthecommandwindowfromwhichtheJavaapplicationexecutes.InMicrosoftWindows95/98/ME,thecommandwindowistheMS-DOSprompt.InMicrosoftWindowsNT/2000,thecommandwindowistheCOMMANDPROMPT(cmd.exe).Thecommandwindowisnormallycalledacommandwindow,acommandtool,ashelltoolorashell.Oncomputersrunninganoperatingsystemthatdoesnothaveacommandwindow(suchasaMacintosh),thejavainterpreternormallydisplaysawindowcontainingtheinformationtheprogramdisplays.MethodSystem.out.printlndisplays(orprints)lineoftextinthecommandwindow.WhenSystem.out.printlncompletesitstask,itautomaticallypositionstheoutputcursor(thelocationwherethenextcharacterwillbedisplayed)tothebeginningtheofthenextlineinthecommandwindow.(ThismoveofthecursorissimilartoyoupressingtheEnterkeywhentypinginatexteditorthecursorappearsatthebeginningofthenextlineinyourfile.)Theentireline,includingSystem.out.println,itsargumentintheparentheses(thestring)andthesemicolon(;),isastatement.Everystatementmustendwithasemicolon(alsoknownasthestatementterminator).ItdisplaysthemessageWelcometoJavaProgramming!inthecommandwindow.Omittingthesemicolonattheendofastatementisasyntaxerror.Erroroccurswhenthecompilercannotrecognizeastatement.Thecompilernormallyissuesanerrormessagetohelptheprogrammeridentifyandfixtheincorrectstatement.Syntaxisviolationsofthelanguagerules.Syntaxerrorsarealsocalledcompileerrors,compile-timeerrororcompilationerrors,becausethecompilerdetectsthemduringthecompilationphase.Youwillbeunabletoexecuteyourprogramuntilyoucorrectallofthesyntaxerrorsinit.Whenthecompilerreportsasyntaxerror,theerrormaynotbeonthelinenumberindicatedbytheerrormessage.First,checkthelineforwhichtheerrorwasreported.Ifthatlinedoesnotcontainsyntaxerrors,checktheprecedingseverallinesintheprogram.Someprogrammersfinditdifficultwhenreadingand/orwritingaprogramtomatch4theleftandrightbraces(and)thatdelimitthebodyofaclassdefinitionoramethoddefinition.Forthisreason,someprogrammersprefertoincludeasingle-linecommentafteraclosingrightbrace()0thatendsamethoddefinitionandafteraclosingrightbracethatendsaclassdefinition.Forexample,line11,/endmethodmainSpecifiestheclosingrightbrace()ofmethodmain,andline13,/endclassWelcome1Specifiestheclosingrightbrace()ofclassWelcome1.Eachcommentindicatesthemethodorclassthattherightbraceterminates.Weusesuchcommentstohelpbeginningprogrammersdeterminewhereeachprogramcomponentterminates.Weusesuchcommentswhenpairsofbracescontainmanystatements,whichmaketheclosingbracesdifficulttoidentify.Someprogrammersprefertofollowtheclosingrightbrace()ofamethodbodyorclassdefinitionwithasingle-linecommentindicatingthemethodorclassdefinitiontowhichthebracebelongs.Thiscommentimprovesprogramreadability.Wearenowreadytocompileandexecuteourprogram.Tocompiletheprogram,weopenacommandwindow,changetothedirectorywheretheprogramisstoredandtypeJavacWelcome1.javaIftheprogramcontainsnosyntaxerrors,theprecedingcommandcreatesanewfilecalledWelcome1.classcontainingtheJavabytecodesthatrepresentourapplication.Thesewillbeinterpretedbythejavainterpreterwhenwetellittoexecutetheprogram,asshownintheMicrosoftWindows2000CommandPrompt.JavaWelcome1Tolaunchthejavainterpreterandindicatethatitshouldloadthe“.class”fileforclassWelcome1.Notethatthe“.class”file-nameextensionisomittedfromtheprecedingcommand;otherwisetheinterpreterwillnotexecutetheprogram.Theinterpreterautomaticallycallsmethodmain.Next,thestatementonline7ofmaindisplays“WelcometoJavaProgramming!”5TheJavacompilergeneratessyntaxerrormessageswhenthesyntaxofaprogramisincorrect.Whenyouarelearninghowtoprogram,sometimesitishelpfulto“break”awordingprogramsoyoucanseetheerrormessagesproducedbythecompiler.Then,whenyouencounterthaterrormessageagain,youwillhaveanideaoftheerrorscause.Tryremovingasemicolonorcurlybracefromtheprogram,thenrecompiletheprogramtoseetheerrormessagesgeneratedbytheomission.1/Displayingmultiplestrings2importjava.applet.Applet;/importAppletclass3importjava.awt.Graphics;/importGraphicsclass4publicclassWelcomeextendsApplet5publicvoidpaint(Graphicsg)67g.drawString(“Welcometo”,25,25);8G.drawString(“JavaProgramming”,25,40);9106中文翻译Java编程介绍Java程序由类和方法构成,程序员可以自己编写Java程序的每一部分。但是,大部分Java程序员利用了Java类库中的类和方法。在Java世界中有两部分需要学习:第一个部分就是Java语言本身,可以用它来编写自己的类和方法;第二个部分是如何使用扩充的Java类库。这个程序表述了Java语言的几种重要特性,我们将详细解释程序的每一行。为了阅读方便,程序中都加上了行号,但这些行号不是Java程序的原有部分。第行执行了程序的“真正工作”,在屏幕上显示“”WelcometoJavaProgramming这一短句。现在,让我们按顺序考虑程序的每一行。第一行:AfirstprograminJava这一行以“”开始,表明本行是一个注释。程序员在程序中加入注释来使程序文档化以及增加程序的可读性。注释还可以帮助其他人阅读和理解你的程序。注释在程序执行时不会导致计算机执行任何动作。Java编译器将忽略注释,并且不会产生任何字节码。“AfirstprograminJava”注释简单地描述了程序的目的。一个以“”开始的注释称为单行注释,因为该注释的作用范围在行尾结束。稍后的中间开始,它能够使这一行的剩余部分(如第行和第行)成为注释。1/AfirstprograminJava2importjava.applet.Applet;/importAppletclass3importjava.awt.Graphics;/importGraphicsclass45publicclassWelcomeextendsApplet6publicvoidpaint(Graphicsg)78g.drawString(“WelcometoJavaProgramming!”,25,25);910每一个程序由一个表明本程序用途的注释开始。Java包括许多预先定义的类,并且在磁盘上将相关的类放入一个目录中,我们称之为软件包。这些软件包称为Java类库或者java应用程序编程接口(API)。下面这两行:importjava.applet.Applet;/importAppletclassimportjava.awt.Graphics;/importGraphicsclass是import语句,用来载入编译一个Java程序所需要的类。这些特定的行告诉编译器从java.applet软件包中载入Applet类,并且从java.awt软件包中载入Graphics累。当用户在Java中创建一个applet时,必须载入Applet类。载入Graphics类的目的是程序可以在屏幕上显示信息。Java的最强大的功能是JavaAPI的各个软件包中含有树木庞大的类,程序员可以重用它们而不必重新开发。我们运用了这些类的大量成员,并且将详细讨论类和软件7包。从类中继承一个JavaAPI的子类之前,请仔细阅读它的说明文档以了叫了解这些类的功能。类用来在程序执行时在内存中实例化(或创建)一个对象是内存中的一个区域。其中存储程序使用的信息。类库主要由编译器的供应商提供,但是许多是由独立的软件供应商提供的。我们的Welcome类用来创建一个执行这个Javaapplet的对象,其中运行这个applet的浏览器创建了Welcome类的一个事例。关键字public使得浏览器能够创建并执行我们的applet在Java中,主要的Applet类(即从Applet中继承的)总是一个public(公有)类型的类。当把applet存入文件时,这个applet的类名将作为文件名的一部分。在本例中,文件名为Welcome.java。如果文件名在拼写
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 单站闪电定位仪在哪些场景应用
- 2025年下半年保险行业策略报告:新增负债成本显著下降板块兼具基本面及资金面催化
- 大型集团不动产管理制度
- 县委宣传部工作管理制度
- 公司行政与后勤管理制度
- 园林公司设计部管理制度
- 卫生院内部医保管理制度
- 制造业公司环保管理制度
- 培训机构资料库管理制度
- 公司财务部现金管理制度
- (高清版)DB21∕T 2487-2015 中尺度对流天气分析技术规范
- 公共设施环境保护管理方案
- 2025年广东广州市越秀区建设街招聘劳动保障监察协管员1人历年高频重点提升(共500题)附带答案详解
- 少年志不渝奋斗正当时
- 2025年中电科太力通信科技限公司招聘高频重点提升(共500题)附带答案详解
- 《城镇用水单位智慧节水系统技术要求》
- 2025年围产期保健工作计划
- 战地记者职业生涯规划
- 喘息性支气管肺炎护理
- 《小儿腹痛》课件
- 《无人机飞行操控技术》项目5 无人直升机飞行操控
评论
0/150
提交评论