版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 寵物寄養(yǎng)中心2025年度會員制寄養(yǎng)服務(wù)協(xié)議3篇
- 2025年度大米產(chǎn)業(yè)鏈上下游資源整合及供應(yīng)鏈管理服務(wù)合同3篇
- 2025年度航空運輸租賃合同范本:全新合作協(xié)議3篇
- 二零二五年度新型木工次結(jié)構(gòu)建筑構(gòu)件加工與施工合同3篇
- 2025貨物采購合同樣書
- 二零二五年度企業(yè)數(shù)字化轉(zhuǎn)型與客戶關(guān)系管理服務(wù)合同3篇
- 2025年度一手新房全款合同簡易版(含智能家居)3篇
- 2025年度農(nóng)村土地置換項目合作協(xié)議書
- 二零二五年度熱處理設(shè)備生產(chǎn)與市場分析合同3篇
- 二零二五年度農(nóng)村危房改造回遷房買賣合同
- 2023-2024學(xué)年廣東省廣州市越秀區(qū)九年級(上)期末語文試卷
- 五年級數(shù)學(xué)下冊 課前預(yù)習(xí)單(人教版)
- 2024-2030年中國石油壓裂支撐劑行業(yè)供需現(xiàn)狀及投資可行性分析報告
- 醫(yī)療企業(yè)未來三年戰(zhàn)略規(guī)劃
- 急診科運用PDCA循環(huán)降低急診危重患者院內(nèi)轉(zhuǎn)運風(fēng)險品管圈QCC專案結(jié)題
- 2024年統(tǒng)編版新教材語文小學(xué)一年級上冊全冊單元測試題及答案(共8單元)
- DB11T 1470-2022 鋼筋套筒灌漿連接技術(shù)規(guī)程
- 護士急診科進修匯報
- 2025年統(tǒng)編版中考語文課內(nèi)文言文《湖心亭看雪》三年中考試題+模擬題(解析版)
- 2024學(xué)年四川省成都天府新區(qū)九年級上學(xué)期一診數(shù)學(xué)模擬試題(原卷版)
- 倉庫勞務(wù)外包方案
評論
0/150
提交評論