Topic 2 Introduction to Java Programming编程知识简介_第1页
Topic 2 Introduction to Java Programming编程知识简介_第2页
Topic 2 Introduction to Java Programming编程知识简介_第3页
Topic 2 Introduction to Java Programming编程知识简介_第4页
Topic 2 Introduction to Java Programming编程知识简介_第5页
已阅读5页,还剩42页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

CS305jIntroductiontoComputingIntroductiontoJavaProgramming1Topic2

IntroductiontoJavaProgramming“WhenaprogramminglanguageiscreatedthatallowsprogrammerstoprograminsimpleEnglish,itwillbediscoveredthatprogrammerscannotspeakEnglish.”

-Anonymous

BasedonslidesforBuildingJavaProgramsbyReges/Stepp,foundat

/stepp/book/

CS305jIntroductiontoComputingIntroductiontoJavaProgramming2WhatWeWillDoTodayWhatarecomputerlanguages?JavaeditorstexteditorandcommandlineBlueJFirstprogrammingconceptsoutputwithprintlnstatementssyntaxanderrorsstructuredalgorithmswithstaticmethodsidentifiers,keywords,andcommentsCS305jIntroductiontoComputingIntroductiontoJavaProgramming3ComputersandComputerLanguagesComputersareeverywherehowmanycomputersdoyouown?Computersareusefulbecausetheyrunvariousprogramsprogramissimplyasetofinstructionstocompletesometaskhowmanydifferentprogramsdoyouuseinaday?CS305jIntroductiontoComputingIntroductiontoJavaProgramming4Definitionsprogram:Asetofinstructionsthataretobecarriedoutbyacomputer.programexecution:Theactofcarryingouttheinstructionscontainedinaprogram.thisisdonebyfeedingtheinstructionstotheCPUprogramminglanguage:Asystematicsetofrulesusedtodescribecomputations,generallyinaformatthatiseditablebyhumans.inthisclasswillareusingJavaCS305jIntroductiontoComputingIntroductiontoJavaProgramming5HighLevelLanguagesComputersarefastPentium4chipfrom2001canperformapproximately1,700,000,000computationspersecondmadeupof42,000,000transistors(aswitchthatisonoroff)ComputersaredumbTheycanonlycarryoutaverylimitedsetofinstructionsontheorderof100orsodependingonthecomputer'sprocessormachinelanguageinstructions,akainstructionsetarchitecture(ISA)Add,Branch,Jump,GetData,GetInstruction,StoreCS305jIntroductiontoComputingIntroductiontoJavaProgramming6MachineCodeJohnvonNeumann-co-authorofpaperin1946withArthurW.BurksandHermannH.Goldstine,"PreliminaryDiscussionoftheLogicalDesignofanElectronicComputingInstrument"Oneofthekeypointsprogramcommandsanddatastoredassequencesofbitsinthecomputer'smemoryAprogram:

1110001100000000

0101011011100000

0110100001000000 0000100000001000 0001011011000100 0001001001100001 0110100001000000

CS305jIntroductiontoComputingIntroductiontoJavaProgramming7SayWhat?ProgrammingwithStringsofbits(1sor0s)isnottheeasiestthingintheworld.Assemblylanguagemnemonicsformachinelanguageinstructions .ORIG x3001 LD R1,x3100 AND R3,R3#0 LD R4,R1 BRn x3008

ADD R3,R3,R4 ADD R1,R1,#1

LD R4,R1 BRnzp x3003CS305jIntroductiontoComputingIntroductiontoJavaProgramming8HighLevelLanguagesAssemblylanguage,stillnotsoeasy,andlotsofcommandstoaccomplishthingsHighLevelComputerLanguagesprovidetheabilitytoaccomplishalotwithfewercommandsthanmachineorassemblylanguageinawaythatishopefullyeasiertounderstandintsum;

intcount=0;

intdone=-1;

while(list[count]!=-1)

sum+=list[count];CS305jIntroductiontoComputingIntroductiontoJavaProgramming9JavaTherearehundredsofhighlevelcomputerlanguages.Java,C++,C,Basic,Fortran,Cobol,Lisp,Perl,Prolog,Eiffel,PythonThecapabilitiesofthelanguagesvarywidely,buttheyallneedawaytododeclarativestatementsconditionalstatementsiterativeorrepetitivestatementsAcompilerisaprogramthatconvertscommandsinhighlevellanguagestomachinelanguageinstructionsCS305jIntroductiontoComputingIntroductiontoJavaProgramming10APictureisWorth…TheInterpreter'saresometimesreferredtoastheJavaVirtualMachinesTheoutputofthecompileris.classfileCS305jIntroductiontoComputingIntroductiontoJavaProgramming11ASimpleJavaProgrampublicclassHello{publicstaticvoidmain(String[]args){System.out.println("HelloWorld!");}}ThiswouldbeinatextfilenamedHello.javaDEMOofwritingandrunningaprogramvianotepadandthecommandlineCS305jIntroductiontoComputingIntroductiontoJavaProgramming12MoreDefinitionscodeorsourcecode:Thesequenceofinstructionsinaparticularprogram.ThecodeinthisprograminstructsthecomputertoprintamessageofHello,world!onthescreen.output:Themessagesprintedtothecomputeruserbyaprogram.console:Thetextboxorwindowontowhichoutputisprinted.CS305jIntroductiontoComputingIntroductiontoJavaProgramming13CompilingandRunningCompiler:aprogramthatconvertsaprograminonelanguagetoanotherlanguagecompilefromC++tomachinecodecompileJavatobytecodeBytecode:alanguageforanimaginarycpuInterpreter:AconvertsoneinstructionorlineofcodefromonelanguagetoanotherandthenexecutesthatinstructionWhenjavaprogramsarerunthebytecodeproducedbythecompilerisfedtoaninterpreterthatconvertsittomachinecodeforaparticularCPUonmymachineitconvertsittoinstructionsforaPentiumcpuCS305jIntroductiontoComputingIntroductiontoJavaProgramming14ThecommandlineTorunaJavaprogramusingyourCommandPrompt:changetothedirectoryofyourprogram cdcompiletheprogram javacHello.javaexecutetheprogram javaHellosourcecode(Hello.java)compilebytecode(Hello.class)executeoutputCS305jIntroductiontoComputingIntroductiontoJavaProgramming15AnotherJavaprogrampublicclassHello2{publicstaticvoidmain(String[]args){System.out.println("Hello,world!");System.out.println();System.out.println("Thisprogramproduces");System.out.println("fourlinesofoutput");}}Thecodeinthisprograminstructsthecomputertoprintfourmessagesonthescreen.CS305jIntroductiontoComputingIntroductiontoJavaProgramming16StructureofJavaprogramspublicclass<name>{publicstaticvoidmain(String[]args){

<statement(s)>;}}EveryexecutableJavaprogramconsistsofaclass...thatcontainsamethodnamedmain...thatcontainsthestatementstobeexecutedThepreviousprogramisaclassnamedHello,whosemainmethodexecutesonestatementnamedSystem.out.printlnCS305jIntroductiontoComputingIntroductiontoJavaProgramming17Javaterminologyclass:

(a)Amodulethatcancontainexecutablecode.

(b)Adescriptionofatypeofobjects.(seenlater)statement:Anexecutablepieceofcodethatrepresentsacompletecommandtothecomputer.everybasicJavastatementendswithasemicolon;method:Anamedsequenceofstatementsthatcanbeexecutedtogethertoperformaparticularactionorcomputation.CS305jIntroductiontoComputingIntroductiontoJavaProgramming18Syntaxandsyntaxerrorssyntax:Thesetoflegalstructuresandcommandsthatcanbeusedinaparticularprogramminglanguage.syntaxerrororcompilererror:Aprobleminthestructureofaprogramthatcausesthecompilertofail.IfyoutypeyourJavaprogramincorrectly,youmayviolateJava'ssyntaxandseeasyntaxerror.publicclassHello{pooblicstaticvoidmain(String[]args){System.owt.println("Hello,world!")_

}}CS305jIntroductiontoComputingIntroductiontoJavaProgramming19CompilerOutputTheprogramonthepreviousslideproducesthefollowingoutputwhenweattempttocompileitH:\summer\Hello.java:2:<identifier>expectedpooblicstaticvoidmain(String[]args){^H:\summer\Hello.java:5:';'expected}^2errorsToolcompletedwithexitcode1compileroutput:CS305jIntroductiontoComputingIntroductiontoJavaProgramming20FixingsyntaxerrorsNoticehowtheerrormessagesaresortofcrypticanddonotalwayshelpusunderstandwhatiswrong: H:\summer\Hello.java:2:<identifier>expected pooblicstaticvoidmain(String[]args){ ^We'dhavepreferredafriendlymessagesuchas,

"Youmisspelled'public'"Thecompilerdoestellusthelinenumberonwhichitfoundtheerror,whichhelpsusfindtheplacetofixthecode.Thelinenumbershownisagoodhint,butisnotalwaysthetruesourceoftheproblem.Javahasafairlyrigidsyntax.CS305jIntroductiontoComputingIntroductiontoJavaProgramming21System.out.printlnJavaprogramsuseastatementcalledSystem.out.printlntoinstructthecomputertoprintalineofoutputontheconsolepronounced"print-linn";sometimescalledaprintlnstatementforshortTwowaystouseSystem.out.println:1.System.out.println("<Message>");Printsthegivenmessageasalineoftextontheconsole.2.System.out.println();Printsablanklineontheconsole.CS305jIntroductiontoComputingIntroductiontoJavaProgramming22Stringsandstringliteralsstring:Asequenceoftextcharacters(notjustletters)thatcanbeprintedormanipulatedinaprogram.literal:arepresentationofavalueofaparticulartypeStringliteralsinJavastartandendwithquotationmarkcharacters

"Thisisastring"CS305jIntroductiontoComputingIntroductiontoJavaProgramming23DetailsaboutStringsAstringliteralmaynotspanacrossmultiplelines.

"Thisisnot

alegalString."Astringmaynotcontaina"character.'isOK

"Thisisnota"legal"Stringeither."

"Thisis'okay'though."Astringcanrepresentcertainspecialcharactersbyprecedingthemwithabackslash\(thisiscalledanescapesequence).\t tabcharacter\n newlinecharacter\" quotationmarkcharacter\\ backslashcharacterCS305jIntroductiontoComputingIntroductiontoJavaProgramming24PracticeProgram1Whatsequenceofprintlnstatementswillgeneratethefollowingoutput?

Thisprogramprintsthefirstlinesofthesong"slots"."Shelivesinatrailer""Ontheoutskirts'aReno""Sheplaysquarterslotsinthelocalscasino."CS305jIntroductiontoComputingIntroductiontoJavaProgramming25PracticeProgram2Whatsequenceofprintlnstatementswillgeneratethefollowingoutput?

A"quoted"Stringis

'much'betterifyoulearn

therulesof"escapesequences."

Also,""representsanemptyString.

Don'tforgettouse\"insteadof"!

''isnotthesameas"CS305jIntroductiontoComputingIntroductiontoJavaProgramming26PracticeProgram3Whatistheoutputofthefollowingprintlnstatements?System.out.println("\ta\tb\tc");System.out.println("\\\\");System.out.println("'");System.out.println("\"\"\"");System.out.println("C:\nin\thedownwardspiral");26CS305jIntroductiontoComputingIntroductiontoJavaProgramming27AnswertoPracticeProgram3Outputofeachprintlnstatement:abc\\'"""C:inhedownwardspiralCS305jIntroductiontoComputingIntroductiontoJavaProgramming28PracticeProgram4Writeaprintlnstatementtoproducethisoutput:/\//\\///\\\CS305jIntroductiontoComputingIntroductiontoJavaProgramming29AnswertoPracticeProgram4printlnstatementtoproducethelineofoutput:System.out.println("/\\//\\\\///\\\\\\");CS305jIntroductiontoComputingIntroductiontoJavaProgramming30AstructuredexampleWhatsequenceofprintlnstatementswillgeneratethefollowingoutput?

_____

/\

/\

\/

\_____/

_____

/\

/\

||

||

||

\/

\_____/

_____

/\

/\

+-------+

_____

/\

/\Whatobservationscanwemakeabouttheoutputthatisgenerated?Ithasanoticeablestructure.

(drawfirstfigure,drawsecondfigure,

drawthirdfigure,...)Theoutputcontainsredundancy.Certainfigures(orlargepartsoffigures)arerepeatedintheoutput.CS305jIntroductiontoComputingIntroductiontoJavaProgramming31StructuredalgorithmsHowdoesonebakesugarcookies?Mixthedryingredients.Creamthebutterandsugar.Beatintheeggs.Stirinthedryingredients.Settheovenfortheappropriatetemperature.Setthetimer.Placethecookiesintotheoven.Allowthecookiestobake.Mixtheingredientsforthefrosting.Spreadfrostingandsprinklesontothecookies....Canweexpressthisprocessinamorestructuredway?CS305jIntroductiontoComputingIntroductiontoJavaProgramming32Astructuredalgorithmstructuredalgorithm:Alistofstepsforsolvingaproblem,whichisbrokendownintocohesivetasks.Astructuredalgorithmforbakingsugarcookies:1.Makethecookiebatter.Mixthedryingredients.Creamthebutterandsugar.Beatintheeggs.Stirinthedryingredients.2.Bakethecookies.Settheovenfortheappropriatetemperature.Setthetimer.Placethecookiesintotheoven.Allowthecookiestobake.3.Addfrostingandsprinkles.Mixtheingredientsforthefrosting.Spreadfrostingandsprinklesontothecookies....CS305jIntroductiontoComputingIntroductiontoJavaProgramming33RedundancyinalgorithmsHowwouldweexpressthestepstobakeadoublebatchofsugarcookies?Unstructured:Mixthedryingredients.Creamthebutterandsugar.Beatintheeggs.Stirinthedryingredients.Settheoven...Setthetimer.Placethefirstbatchofcookiesintotheoven.Allowthecookiestobake.Settheoven...Setthetimer.Placethesecondbatchofcookiesintotheoven.Allowthecookiestobake.Mixtheingredientsforthefrosting.Structured:1.Makethecookiebatter.2a.Bakethefirstbatchofcookies.2b.Bakethesecondbatchofcookies.3.Addfrostingandsprinkles.Observation:Astructuredalgorithmnotonlypresentstheprobleminahierarchicalwaythatiseasiertounderstand,butitalsoprovideshigher-leveloperationswhichhelpeliminateredundancyinthealgorithm.CS305jIntroductiontoComputingIntroductiontoJavaProgramming34Staticmethodsstaticmethod:Agroupofstatementsthatisgivenanamesothatitcanbeexecutedinourprogram.Breakingdownaproblemintostaticmethodsisalsocalled"proceduraldecomposition."

Usingastaticmethodrequirestwosteps:declareit(writedowntherecipe)Whenwedeclareastaticmethod,wewritea

groupofstatementsandgiveitaname.callit(cookusingtherecipe)Whenwecallastaticmethod,wetellourmainmethod

toexecutethestatementsinthatstaticmethod.Staticmethodsareusefulfor:denotingthestructureofalargerprograminsmaller,moreunderstandablepieceseliminatingredundancythroughreuseCS305jIntroductiontoComputingIntroductiontoJavaProgramming35StaticmethodsyntaxThestructureofastaticmethod:

publicclass<ClassName>{

publicstaticvoid<Methodname>(){

<statements>;

}

}Example:

publicstaticvoidprintCheer(){

System.out.println(“ThreecheersforPirates!");

System.out.println(“Huzzah!");

System.out.println(“Huzzah!");

System.out.println(“Huzzah!");

}CS305jIntroductiontoComputingIntroductiontoJavaProgramming36StaticmethodsexamplepublicclassTwoMessages{publicstaticvoidmain(String[]args){printCheer();System.out.println();printCheer();} publicstaticvoidprintCheer(){

System.out.println(“ThreecheersforPirates!");

System.out.println(“Huzzah!");

System.out.println(“Huzzah!");

System.out.println(“Huzzah!");

}}Program'soutput:ThreecheersforPirates!Huzzah!Huzzah!Huzzah!

ThreecheersforPirates!Huzzah!Huzzah!Huzzah!CS305jIntroductiontoComputingIntroductiontoJavaProgramming37MethodscallingeachotherOnestaticmethodmaycallanother:publicclassTwelveDays{publicstaticvoidmain(String[]args){day1();day2();}publicstaticvoidday1(){System.out.println("Apartridgeinapeartree.");}publicstaticvoidday2(){System.out.println("Twoturtledoves,and");day1();}}Program'soutput:Apartridgeinapeartree.Twoturtledoves,andApartridgeinapeartree.CS305jIntroductiontoComputingIntroductiontoJavaProgramming38ControlflowofmethodsWhenamethodiscalled,aJavaprogram'jumps'intothatmethod,executesallofitsstatements,andthen'jumps'backtowhereitstarted.publicclassTwelveDays{publicstaticvoidmain(String[]args){day1();

day2();}

}publicstaticvoidday1(){System.out.println("Apartridgeinapeartree.");}publicstaticvoidday2(){System.out.println("Twoturtledoves,and");day1();}CS305jIntroductiontoComputingIntroductiontoJavaProgramming39StaticmethodproblemsWriteaprogramthatprintsthefollowingoutputtotheconsole.Usestaticmethodsasappropriate.Idonotlikegreeneggsandham,Idonotlikethem,SamIam!Idonotlikethemonboat,Idonotlikethemwithagoat.Idonotlikegreeneggsandham,Idonotlikethem,SamIam!Writeaprogramthatprintsthefollowingoutputtotheconsole.Usestaticmethodsasappropriate.Lollipop,lollipopOh,lollilollilolliLollipop,lollipopOh,lollilollilolliCallmybabylollipopCS305jIntroductiontoComputingIntroductiontoJavaProgramming40WhentousestaticmethodsYoushouldplaceagroupofstatementsintoastaticmethodifanyofthefollowingconditionsismet:Thestatementsarerelatedtoeachotherandformacombinedpartoftheprogram'sstructure.Thestatementsarerepeatedintheprogram.Youneednotcreatestaticmethodsforthefollowing:Individualstatements.

(Onesingleprintlninitsownstaticmethoddoesnotimprovetheprogram,andmaymakeithardertoread.)Unrelatedorweaklyrelatedstatements.

(Ifthestatementsarenotcloselyrelated,considersplittingthemethodintotwoormoresmallermethods.)Onlyblanklines.

(It'sfinetohaveblankSystem.out.println();statementsinthemainmethod.)Remember,theseareguidelines!CS305jIntroductiontoComputingIntroductiontoJavaProgramming41Identifiersidentifier:Anamethatwegivetoapieceofdataorpartofaprogram.Identifiersareusefulbecausetheyallowustorefertothatdataorcodelaterintheprogram.Identifiersgivenamesto:classesmethodsvariables(namedpiecesofdata;seenlater)Thenameyougivetoastaticmethodisanexampleofanidentifier.Whataresomeotherexampleidentifierwe'veseen?CS305jIntroductiontoComputingIntroductiontoJavaProgramming42DetailsaboutidentifiersJavaidentifiernames:firstcharactermustaletteror_or$followingcharacterscanbeanyofthosecharactersoranumberidentifiersarecase-sensitive;nameisdifferentfromNameExampleJavaidentifiers:legal: oliviasecond_place_myName

TheCureANSWER_IS_42$variableillegal: me+u:-)question?

side-swipehithereph.d

belles's2%milkkelly@

explainwhyeachoftheaboveidentifiersisnotlegal.CS305jIntroductiontoComputingIntroductiontoJavaProgramming43Keywordskeyword:Anidentifierthatyoucannotuse,becauseitalreadyhasareservedmeaningintheJavalanguage.CompletelistofJavakeywords:abstractdefaultifprivatethisbooleandoimplementsprotectedthrowbreakdoubleimportpublicthrowsbyteelseinstanceofreturntransientcaseextendsintshorttrycatchfinalinterfacestatic

voidcharfinallylongstrictfpvolatileclassfloatnativesuperwhileconstfornewswitchcontinuegotopackagesynchronizedYoumaynotusecharorwhileorthisoranyotherkeywordforthenameofaclassormethod;Javareservesthosewordstomeanotherthings.YoucoulduseCHAR,While,orThIs,becauseJavaiscase-sensitive.However,thiscouldbeconfusingandisnotrecommended.CS305jIntroductiontoComputingIntroductiontoJavaProgramming44Commentscomment:Anotewritteninthesourcecodebytheprogrammertomakethecodeeasiertounderstand.Commentsarenotexecutedwhenyourprogramruns.MostJavaeditorsturnyourcommentsaspecialcolortomakeiteasiertoidentifythem.Comment,generalsyntax:

/*<commenttext;mayspanmultiplelines>

*/ or,

//<commenttext,ononeline>Examples:/*Acommentgoeshere.*//*Itcanevenspan

multiplelines.*///Thisisaone-linecomment.CS305jIntroductiontoComputingIntroductiontoJavaProgramming45Usingcomments

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论