java語言程序設(shè)計(jì)-基礎(chǔ)篇-課件(第5章)英文_第1頁
java語言程序設(shè)計(jì)-基礎(chǔ)篇-課件(第5章)英文_第2頁
java語言程序設(shè)計(jì)-基礎(chǔ)篇-課件(第5章)英文_第3頁
java語言程序設(shè)計(jì)-基礎(chǔ)篇-課件(第5章)英文_第4頁
java語言程序設(shè)計(jì)-基礎(chǔ)篇-課件(第5章)英文_第5頁
已閱讀5頁,還剩72頁未讀 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

Chapter5Methods1Chapter5Methods1OpeningProblemFindthesumofintegersfrom1to10,from20to30,andfrom35to45,respectively.2OpeningProblemFindthesumofProblemintsum=0;for(inti=1;i<=10;i++)sum+=i;System.out.println("Sumfrom1to10is"+sum);sum=0;for(inti=20;i<=30;i++)sum+=i;System.out.println("Sumfrom20to30is"+sum);sum=0;for(inti=35;i<=45;i++)sum+=i;System.out.println("Sumfrom35to45is"+sum);3Problemintsum=0;3Problemintsum=0;for(inti=1;i<=10;i++)sum+=i;System.out.println("Sumfrom1to10is"+sum);sum=0;for(inti=20;i<=30;i++)sum+=i;System.out.println("Sumfrom20to30is"+sum);sum=0;for(inti=35;i<=45;i++)sum+=i;System.out.println("Sumfrom35to45is"+sum);4Problemintsum=0;4Solutionpublicstaticintsum(inti1,inti2){intsum=0;for(inti=i1;i<=i2;i++)sum+=i;returnsum;}publicstaticvoidmain(String[]args){System.out.println("Sumfrom1to10is"+sum(1,10));System.out.println("Sumfrom20to30is"+sum(20,30));System.out.println("Sumfrom35to45is"+sum(35,45));}5Solutionpublicstaticintsum(ObjectivesTodefinemethods,invokemethods,andpassargumentstoamethod(§5.2-5.5).Todevelopreusablecodethatismodular,easy-to-read,easy-to-debug,andeasy-to-maintain.(§5.6).Tousemethodoverloadingandunderstandambiguousoverloading(§5.7).Todesignandimplementoverloadedmethods(§5.8).Todeterminethescopeofvariables(§5.9).ToknowhowtousethemethodsintheMathclass(§§5.10-5.11).Tolearntheconceptofmethodabstraction(§5.12).Todesignandimplementmethodsusingstepwiserefinement(§5.12).6ObjectivesTodefinemethods,iDefiningMethodsAmethodisacollectionofstatementsthataregroupedtogethertoperformanoperation.7DefiningMethodsAmethodisaMethodSignatureMethodsignatureisthecombinationofthemethodnameandtheparameterlist.8MethodSignatureMethodsignatuFormalParametersThevariablesdefinedinthemethodheaderareknownasformalparameters.9FormalParametersThevariablesActualParametersWhenamethodisinvoked,youpassavaluetotheparameter.Thisvalueisreferredtoasactualparameterorargument.10ActualParametersWhenamethodReturnValueTypeAmethodmayreturnavalue.ThereturnValueTypeisthedatatypeofthevaluethemethodreturns.Ifthemethoddoesnotreturnavalue,thereturnValueTypeisthekeywordvoid.Forexample,thereturnValueTypeinthemainmethodisvoid.11ReturnValueTypeAmethodmayCallingMethodsTestingthemaxmethodThisprogramdemonstratescallingamethodmaxtoreturnthelargestoftheintvaluesTestMax12CallingMethodsTestingthemaxCallingMethods,cont.animation13CallingMethods,cont.animatioTraceMethodInvocationiisnow5animation14TraceMethodInvocationiisnoTraceMethodInvocationjisnow2animation15TraceMethodInvocationjisnoTraceMethodInvocationinvokemax(i,j)animation16TraceMethodInvocationinvokeTraceMethodInvocationinvokemax(i,j)Passthevalueofitonum1Passthevalueofjtonum2animation17TraceMethodInvocationinvokeTraceMethodInvocationdeclarevariableresultanimation18TraceMethodInvocationdeclareTraceMethodInvocation(num1>num2)istruesincenum1is5andnum2is2animation19TraceMethodInvocation(num1>TraceMethodInvocationresultisnow5animation20TraceMethodInvocationresultTraceMethodInvocationreturnresult,whichis5animation21TraceMethodInvocationreturnTraceMethodInvocationreturnmax(i,j)andassignthereturnvaluetokanimation22TraceMethodInvocationreturnTraceMethodInvocationExecutetheprintstatementanimation23TraceMethodInvocationExecuteCAUTIONAreturnstatementisrequiredforavalue-returningmethod.Themethodshownbelowin(a)islogicallycorrect,butithasacompilationerrorbecausetheJavacompilerthinksitpossiblethatthismethoddoesnotreturnanyvalue.Tofixthisproblem,deleteif(n<0)in(a),sothatthecompilerwillseeareturnstatementtobereachedregardlessofhowtheifstatementisevaluated.24CAUTIONAreturnstatementisrReuseMethodsfromOtherClassesNOTE:Oneofthebenefitsofmethodsisforreuse.ThemaxmethodcanbeinvokedfromanyclassbesidesTestMax.IfyoucreateanewclassTest,youcaninvokethemaxmethodusingClassName.methodName(e.g.,TestMax.max).25ReuseMethodsfromOtherClassCallStacks26CallStacks26TraceCallStackiisdeclaredandinitializedanimation27TraceCallStackiisdeclaredTraceCallStackjisdeclaredandinitializedanimation28TraceCallStackjisdeclaredTraceCallStackDeclarekanimation29TraceCallStackDeclarekanimaTraceCallStackInvokemax(i,j)animation30TraceCallStackInvokemax(i,TraceCallStackpassthevaluesofiandjtonum1andnum2animation31TraceCallStackpassthevalueTraceCallStackpassthevaluesofiandjtonum1andnum2animation32TraceCallStackpassthevalueTraceCallStack(num1>num2)istrueanimation33TraceCallStack(num1>num2)TraceCallStackAssignnum1toresultanimation34TraceCallStackAssignnum1toTraceCallStackReturnresultandassignittokanimation35TraceCallStackReturnresultTraceCallStackExecuteprintstatementanimation36TraceCallStackExecuteprintvoidMethodExampleThistypeofmethoddoesnotreturnavalue.Themethodperformssomeactions.TestVoidMethod37voidMethodExampleThistypeoPassingParameterspublicstaticvoidnPrintln(Stringmessage,intn){for(inti=0;i<n;i++)System.out.println(message);}SupposeyouinvokethemethodusingnPrintln(“WelcometoJava”,5);Whatistheoutput?SupposeyouinvokethemethodusingnPrintln(“ComputerScience”,15);Whatistheoutput?38PassingParameterspublicstatiPassbyValueThisprogramdemonstratespassingvaluestothemethods.Increment39PassbyValueThisprogramdemoPassbyValueTestingPassbyvalueThisprogramdemonstratespassingvaluestothemethods.TestPassByValue40PassbyValueTestingPassbyvPassbyValue,cont.41PassbyValue,cont.41ModularizingCodeMethodscanbeusedtoreduceredundantcodingandenablecodereuse.Methodscanalsobeusedtomodularizecodeandimprovethequalityoftheprogram.GreatestCommonDivisorMethodPrimeNumberMethod42ModularizingCodeMethodscanbOverloadingMethodsOverloadingthemaxMethodpublicstaticdoublemax(doublenum1,doublenum2){if(num1>num2)returnnum1;elsereturnnum2;}TestMethodOverloading43OverloadingMethodsOverloadingAmbiguousInvocationSometimestheremaybetwoormorepossiblematchesforaninvocationofamethod,butthecompilercannotdeterminethemostspecificmatch.Thisisreferredtoasambiguousinvocation.Ambiguousinvocationisacompilationerror.44AmbiguousInvocationSometimesAmbiguousInvocationpublicclassAmbiguousOverloading{publicstaticvoidmain(String[]args){System.out.println(max(1,2));}

publicstaticdoublemax(intnum1,doublenum2){if(num1>num2)returnnum1;elsereturnnum2;}

publicstaticdoublemax(doublenum1,intnum2){if(num1>num2)returnnum1;elsereturnnum2;}}45AmbiguousInvocationpublicclaProblem:ConvertingDecimalstoHexadecimalsWriteamethodthatconvertsadecimalintegertoahexadecimal.Decimal2HexConversion46Problem:ConvertingDecimalstScopeofLocalVariablesAlocalvariable:avariabledefinedinsideamethod.Scope:thepartoftheprogramwherethevariablecanbereferenced.Thescopeofalocalvariablestartsfromitsdeclarationandcontinuestotheendoftheblockthatcontainsthevariable.Alocalvariablemustbedeclaredbeforeitcanbeused.47ScopeofLocalVariablesAlocaScopeofLocalVariables,cont.Youcandeclarealocalvariablewiththesamenamemultipletimesindifferentnon-nestingblocksinamethod,butyoucannotdeclarealocalvariabletwiceinnestedblocks.48ScopeofLocalVariables,contScopeofLocalVariables,cont.Avariabledeclaredintheinitialactionpartofaforloopheaderhasitsscopeintheentireloop.Butavariabledeclaredinsideaforloopbodyhasitsscopelimitedintheloopbodyfromitsdeclarationandtotheendoftheblockthatcontainsthevariable.49ScopeofLocalVariables,contScopeofLocalVariables,cont.50ScopeofLocalVariables,contScopeofLocalVariables,cont.//FinewithnoerrorspublicstaticvoidcorrectMethod(){intx=1;inty=1;//iisdeclaredfor(inti=1;i<10;i++){x+=i;}//iisdeclaredagainfor(inti=1;i<10;i++){y+=i;}}51ScopeofLocalVariables,contScopeofLocalVariables,cont.//WithnoerrorspublicstaticvoidincorrectMethod(){intx=1;inty=1;for(inti=1;i<10;i++){intx=0;x+=i;}}52ScopeofLocalVariables,contMethodAbstractionYoucanthinkofthemethodbodyasablackboxthatcontainsthedetailedimplementationforthemethod.53MethodAbstractionYoucanthinBenefitsofMethodsWriteamethodonceandreuseitanywhere.Informationhiding.Hidetheimplementationfromtheuser.Reducecomplexity.54BenefitsofMethodsWriteametTheMathClassClassconstants:PIEClassmethods:TrigonometricMethodsExponentMethodsRoundingMethodsmin,max,abs,andrandomMethods55TheMathClassClassconstants:TrigonometricMethodssin(doublea)cos(doublea)tan(doublea)acos(doublea)asin(doublea)atan(doublea)RadianstoRadians(90)Examples:Math.sin(0)returns0.0Math.sin(Math.PI/6)returns0.5Math.sin(Math.PI/2)returns1.0Math.cos(0)returns1.0Math.cos(Math.PI/6)returns0.866Math.cos(Math.PI/2)returns056TrigonometricMethodssin(doublExponentMethodsexp(doublea)Returnseraisedtothepowerofa.log(doublea)Returnsthenaturallogarithmofa.log10(doublea)Returnsthe10-basedlogarithmofa.pow(doublea,doubleb)Returnsaraisedtothepowerofb.sqrt(doublea)Returnsthesquarerootofa.Examples:Math.exp(1)returns2.71Math.log(2.71)returns1.0Math.pow(2,3)returns8.0Math.pow(3,2)returns9.0Math.pow(3.5,2.5)returns22.91765Math.sqrt(4)returns2.0Math.sqrt(10.5)returns3.2457ExponentMethodsexp(doublea)ERoundingMethodsdoubleceil(doublex)xroundeduptoitsnearestinteger.Thisintegerisreturnedasadoublevalue.doublefloor(doublex)xisroundeddowntoitsnearestinteger.Thisintegerisreturnedasadoublevalue.doublerint(doublex)xisroundedtoitsnearestinteger.Ifxisequallyclosetotwointegers,theevenoneisreturnedasadouble.intround(floatx)Return(int)Math.floor(x+0.5).longround(doublex)Return(long)Math.floor(x+0.5).

58RoundingMethodsdoubleceil(doRoundingMethodsExamplesMath.ceil(2.1)returns3.0Math.ceil(2.0)returns2.0Math.ceil(-2.0)returns–2.0Math.ceil(-2.1)returns-2.0Math.floor(2.1)returns2.0Math.floor(2.0)returns2.0Math.floor(-2.0)returns–2.0Math.floor(-2.1)returns-3.0Math.rint(2.1)returns2.0Math.rint(2.0)returns2.0Math.rint(-2.0)returns–2.0Math.rint(-2.1)returns-2.0Math.rint(2.5)returns2.0Math.rint(-2.5)returns-2.0Math.round(2.6f)returns3Math.round(2.0)returns2Math.round(-2.0f)returns-2Math.round(-2.6)returns-3

59RoundingMethodsExamplesMath.min,max,andabsmax(a,b)andmin(a,b)Returnsthemaximumorminimumoftwoparameters.abs(a)Returnstheabsolutevalueoftheparameter.random()Returnsarandomdoublevalue

intherange[0.0,1.0).Examples:Math.max(2,3)returns3Math.max(2.5,3)returns3.0Math.min(2.5,3.6)returns2.5Math.abs(-2)returns2Math.abs(-2.1)returns2.160min,max,andabsmax(a,b)andTherandomMethodGeneratesarandomdoublevaluegreaterthanorequalto0.0andlessthan1.0(0<=Math.random()<1.0).Examples:Ingeneral,61TherandomMethodGeneratesarCaseStudy:GeneratingRandomCharactersComputerprogramsprocessnumericaldataandcharacters.Youhaveseenmanyexamplesthatinvolvenumericaldata.Itisalsoimportanttounderstandcharactersandhowtoprocessthem.AsintroducedinSection2.9,eachcharacterhasauniqueUnicodebetween0andFFFFinhexadecimal(65535indecimal).Togeneratearandomcharacteristogeneratearandomintegerbetween0and65535usingthefollowingexpression:(notethatsince0<=Math.random()<1.0,youhavetoadd1to65535.)(int)(Math.random()*(65535+1))62CaseStudy:GeneratingRandomCaseStudy:GeneratingRandomCharacters,cont.Nowletusconsiderhowtogeneratearandomlowercaseletter.TheUnicodeforlowercaselettersareconsecutiveintegersstartingfromtheUnicodefor'a',thenfor'b','c',...,and'z'.TheUnicodefor'a'is(int)'a'So,arandomintegerbetween(int)'a'and(int)'z'is(int)((int)'a'+Math.random()*((int)'z'-(int)'a'+1)63CaseStudy:GeneratingRandomCaseStudy:GeneratingRandomCharacters,cont.Nowletusconsiderhowtogeneratearandomlowercaseletter.TheUnicodeforlowercaselettersareconsecutiveintegersstartingfromtheUnicodefor'a',thenfor'b','c',...,and'z'.TheUnicodefor'a'is(int)'a'So,arandomintegerbetween(int)'a'and(int)'z'is(int)((int)'a'+Math.random()*((int)'z'-(int)'a'+1)64CaseStudy:GeneratingRandomCaseStudy:GeneratingRandomCharacters,cont.AsdiscussedinChapter2.,allnumericoperatorscanbeappliedtothecharoperands.Thecharoperandiscastintoanumberiftheotheroperandisanumberoracharacter.So,theprecedingexpressioncanbesimplifiedasfollows:'a'+Math.random()*('z'-'a'+1)

Soarandomlowercaseletteris(char)('a'+Math.random()*('z'-'a'+1))65CaseStudy:GeneratingRandomCaseStudy:GeneratingRandomCharacters,cont.Togeneralizetheforegoingdiscussion,arandomcharacterbetweenanytwocharactersch1andch2withch1<ch2canbegeneratedasfollows:(char)(ch1+Math.random()*(ch2–ch1+1))

66CaseStudy:GeneratingRandomTheRandomCharacterClass//RandomCharacter.java:GeneraterandomcharacterspublicclassRandomCharacter{/**Generatearandomcharacterbetweench1andch2*/publicstaticchargetRandomCharacter(charch1,charch2){return(char)(ch1+Math.random()*(ch2-ch1+1));}

/**Generatearandomlowercaseletter*/publicstaticchargetRandomLowerCaseLetter(){returngetRandomCharacter('a','z');}

/**Generatearandomuppercaseletter*/publicstaticchargetRandomUpperCaseLetter(){returngetRandomCharacter('A','Z');}

/**Generatearandomdigitcharacter*/publicstaticchargetRandomDigitCharacter(){returngetRandomCharacter('0','9');}

/**Generatearandomcharacter*/publicstaticchargetRandomCharacter(){returngetRandomCharacter('\u0000','\uFFFF');}}TestRandomCharacterRandomCharacter67TheRandomCharacterClass//RaStepwiseRefinement(Optional)Theconc

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論