java语言程序设计 基础篇课件(第3章)英文

PPT
  • 阅读 123 次
  • 下载 0 次
  • 页数 69 页
  • 大小 669.508 KB
  • 2022-12-05 上传
  • 收藏
  • 违规举报
  • © 版权认领
下载文档30.00 元 加入VIP免费下载
此文档由【小橙橙】提供上传,收益归文档提供者,本网站只提供存储服务。若此文档侵犯了您的版权,欢迎进行违规举报版权认领
java语言程序设计 基础篇课件(第3章)英文
可在后台配置第一页与第二页中间广告代码
java语言程序设计 基础篇课件(第3章)英文
可在后台配置第二页与第三页中间广告代码
java语言程序设计 基础篇课件(第3章)英文
可在后台配置第三页与第四页中间广告代码
java语言程序设计 基础篇课件(第3章)英文
java语言程序设计 基础篇课件(第3章)英文
还剩10页未读,继续阅读
【这是免费文档,您可以免费阅读】
/ 69
  • 收藏
  • 违规举报
  • © 版权认领
下载文档30.00 元 加入VIP免费下载
文本内容

【文档说明】java语言程序设计 基础篇课件(第3章)英文.ppt,共(69)页,669.508 KB,由小橙橙上传

转载请保留链接:https://www.ichengzhen.cn/view-92601.html

以下为本文档部分文字说明:

Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Chapter3Selections

1Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807MotivationsIfyoua

ssignedanegativevalueforradiusinListing2.1,ComputeArea.java,theprogramwouldprintaninvalidresult.Iftheradiusisnegative,y

oudon'twanttheprogramtocomputethearea.Howcanyoudealwiththissituation?2Liang,IntroductiontoJavaProgramming,Eigh

thEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Objectives3Todeclarebooleantypeand

writeBooleanexpressionsusingcomparisonoperators(§3.2).ToprogramAdditionQuizusingBooleanexpressions(§3.3).Toimplementselectionco

ntrolusingone-wayifstatements(§3.4)ToprogramtheGuessBirthdaygameusingone-wayifstatements(§3.5).Toimplementselectioncontro

lusingtwo-wayifstatements(§3.6).Toimplementselectioncontrolusingnestedifstatements(§3.7).Toavoidcommonerrorsin

ifstatements(§3.8).Toprogramusingselectionstatementsforavarietyofexamples(BMI,ComputeTax,SubtractionQuiz)(§3.9-3.11).Togeneraterandomnumbersusin

gtheMath.random()method(§3.9).Tocombineconditionsusinglogicaloperators(&&,||,and!)(§3.12).Toprogramusingselection

statementswithcombinedconditions(LeapYear,Lottery)(§§3.13-3.14).Toimplementselectioncontrolusingswitchstatements(§3.15).Towriteexpress

ionsusingtheconditionaloperator(§3.16).ToformatoutputusingtheSystem.out.printfmethodandtoformatstringsusingtheString.formatmethod(§3.17).Toexami

netherulesgoverningoperatorprecedenceandassociativity(§3.18).(GUI)Togetuserconfirmationusingconfirmationdialogs(§3.

19).Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.

0132130807ThebooleanTypeandOperatorsOfteninaprogramyouneedtocomparetwovalues,suchaswhetheriisgreaterthanj.Javap

rovidessixcomparisonoperators(alsoknownasrelationaloperators)thatcanbeusedtocomparetwovalues.TheresultofthecomparisonisaBo

oleanvalue:trueorfalse.booleanb=(1>2);4Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEduca

tion,Inc.Allrightsreserved.0132130807ComparisonOperators5OperatorName<lessthan<=lessthanorequalto>greatertha

n>=greaterthanorequalto==equalto!=notequaltoLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrights

reserved.0132130807Problem:ASimpleMathLearningTool6AdditionQuizRunThisexamplecreatesaprogramtoletafirstgraderpracticeadditions.Thepro

gramrandomlygeneratestwosingle-digitintegersnumber1andnumber2anddisplaysaquestionsuchas“Whatis7+9?”tothestudent.Aft

erthestudenttypestheanswer,theprogramdisplaysamessagetoindicatewhethertheansweristrueorfalse.Liang,IntroductiontoJavaProgramming,Eig

hthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807One-wayifStatementsif(boolean-expression){statement(s);}7Bool

eanExpressiontrueStatement(s)false(radius>=0)truearea=radius*radius*PI;System.out.println("Theareaforthecircleof"+"

radius"+radius+"is"+area);false(A)(B)if(radius>=0){area=radius*radius*PI;System.out.println("Thearea"+"forthecircleofradiu

s"+radius+"is"+area);}Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.All

rightsreserved.0132130807Note8ifi>0{System.out.println("iispositive");}(a)Wrong(b)Correctif(i>0){System.out.println("iispos

itive");}if(i>0){System.out.println("iispositive");}(a)Equivalent(b)if(i>0)System.out.println("iispositive");Liang,IntroductiontoJavaProgr

amming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807SimpleifDemo9SimpleIfDemoRunWriteaprogramthatpromptstheusertoenterani

nteger.Ifthenumberisamultipleof5,printHiFive.Ifthenumberisdivisibleby2,printHiEven.Liang,IntroductiontoJavaProgrammin

g,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Problem:GuessingBirthdayTheprogramcanguessyourbirthdate.Runtoseehowitwo

rks.10GuessBirthdayRun16171819202122232425262728293031Set1891011121314152425262728293031Set2135791113151719212325272931S

et32367101114151819222326273031Set44567121314152021222328293031Set5+=19Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEduc

ation,Inc.Allrightsreserved.0132130807MathematicsBasisfortheGame19is10011inbinary.7is111inbinary.23is11101inbinary11161

71819202122232425262728293031Set1891011121314152425262728293031Set2135791113151719212325272931Set32367101114151819222326273031Set4456712131

4152021222328293031Set5+=191000010+1100110011010+100111197100001000100+11110123Liang,IntroductiontoJavaProgramming,Eighth

Edition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807TheTwo-wayifStatementif(boolean-expression){statement(s)-f

or-the-true-case;}else{statement(s)-for-the-false-case;}12BooleanExpressionfalsetrueStatement(s)forthefalsecaseStatement

(s)forthetruecaseLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807if...elseExa

mpleif(radius>=0){area=radius*radius*3.14159;System.out.println("Theareaforthe“+“circleofradius"+radius+"

is"+area);}else{System.out.println("Negativeinput");}13Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrigh

tsreserved.0132130807MultipleAlternativeifStatements14if(score>=90.0)grade='A';elseif(score>=80.0)grade='B';elseif(score>=70.0)grade='C';el

seif(score>=60.0)grade='D';elsegrade='F';Equivalentif(score>=90.0)grade='A';elseif(score>=80.0)grade='B';elseif(score>=70.0)grade='C';e

lseif(score>=60.0)grade='D';elsegrade='F';Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.013213080

7Traceif-elsestatement15if(score>=90.0)grade='A';elseif(score>=80.0)grade='B';elseif(score>=70.0)grade='C';elseif(score>=60.0)grade='D';e

lsegrade='F';Supposescoreis70.0TheconditionisfalseanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)201

1PearsonEducation,Inc.Allrightsreserved.0132130807Traceif-elsestatement16if(score>=90.0)grade='A';elseif(score>=

80.0)grade='B';elseif(score>=70.0)grade='C';elseif(score>=60.0)grade='D';elsegrade='F';Supposescoreis70.0Theconditionisfalseanimation

Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Tra

ceif-elsestatement17if(score>=90.0)grade='A';elseif(score>=80.0)grade='B';elseif(score>=70.0)grade='C';elseif(score>=60.0)grade='D';els

egrade='F';Supposescoreis70.0TheconditionistrueanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011P

earsonEducation,Inc.Allrightsreserved.0132130807Traceif-elsestatement18if(score>=90.0)grade='A';elseif(score>=80.0)

grade='B';elseif(score>=70.0)grade='C';elseif(score>=60.0)grade='D';elsegrade='F';Supposescoreis70.0gradeisCanimationLiang,IntroductiontoJavaP

rogramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceif-elsestatement19if(score>=90.0)grade='A';elseif(score>=80

.0)grade='B';elseif(score>=70.0)grade='C';elseif(score>=60.0)grade='D';elsegrade='F';Supposescoreis70.0ExittheifstatementanimationLia

ng,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807NoteTh

eelseclausematchesthemostrecentifclauseinthesameblock.20inti=1;intj=2;intk=3;if(i>j)if(i>k)System.out.

println("A");elseSystem.out.println("B");(a)Equivalent(b)inti=1;intj=2;intk=3;if(i>j)if(i>k)System.out.prin

tln("A");elseSystem.out.println("B");Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEduca

tion,Inc.Allrightsreserved.0132130807Note,cont.Nothingisprintedfromtheprecedingstatement.Toforcetheelseclausetomatchth

efirstifclause,youmustaddapairofbraces:inti=1;intj=2;intk=3;if(i>j){if(i>k)System.out.println("A");}elseSystem.out.println

("B");ThisstatementprintsB.21Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807CommonErrorsA

ddingasemicolonattheendofanifclauseisacommonmistake.if(radius>=0);{area=radius*radius*PI;System.out.println("Theareaforthecircleofradius"+r

adius+"is"+area);}Thismistakeishardtofind,becauseitisnotacompilationerrororaruntimeerror,itisalogicerror

.Thiserroroftenoccurswhenyouusethenext-lineblockstyle.22WrongLiang,IntroductiontoJavaProgramming,EighthEdition,(c)20

11PearsonEducation,Inc.Allrightsreserved.0132130807TIP23if(number%2==0)even=true;elseeven=false;(a)Equivalentbooleaneven=

number%2==0;(b)Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807CAUTION24if(even==true

)System.out.println("Itiseven.");(a)Equivalentif(even)System.out.println("Itiseven.");(b)Liang,Introductionto

JavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Problem:AnImprovedMathLearningToolThisexamp

lecreatesaprogramtoteachafirstgradechildhowtolearnsubtractions.Theprogramrandomlygeneratestwosingle-digitintegersnumber1andnumber2withnumber1>number

2anddisplaysaquestionsuchas“Whatis9–2?”tothestudent.Afterthestudenttypestheanswerintheinputdialogbox,theprogramdisplaysamessagedialogboxtoindicatew

hethertheansweriscorrect.25SubtractionQuizRunLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEdu

cation,Inc.Allrightsreserved.0132130807Problem:BodyMassIndexBodyMassIndex(BMI)isameasureofhealthonweight.Itcanb

ecalculatedbytakingyourweightinkilogramsanddividingbythesquareofyourheightinmeters.TheinterpretationofBMIforpeople16yearsorolderisasfollows:2

6ComputeBMIRunBMIInterpretationbelow16seriousunderweight16-18underweight18-24normalweight24-29overweight29-35serio

uslyoverweightabove35gravelyoverweightLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.All

rightsreserved.0132130807Problem:ComputingTaxesTheUSfederalpersonalincometaxiscalculatedbasedonthefilingstatusandtaxableincome.Therearefourfi

lingstatuses:singlefilers,marriedfilingjointly,marriedfilingseparately,andheadofhousehold.Thetaxratesfor2009areshownbelow.27MarginalTaxRateSingl

eMarriedFilingJointlyorQualifiedWidow(er)MarriedFilingSeparatelyHeadofHousehold10%$0–$8,350$0–$16,700$0–$8,350$0–$11,95015%$8,

351–$33,950$16,701–$67,900$8,351–$33,950$11,951–$45,50025%$33,951–$82,250$67,901–$137,050$33,951–$68,525$45,501–$117,45028%$82,25

1–$171,550$137,051–$208,850$68,525–$104,425$117,451–$190,20033%$171,551–$372,950$208,851–$372,950$104,

426–$186,475$190,201-$372,95035%$372,951+$372,951+$186,476+$372,951+Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011Pea

rsonEducation,Inc.Allrightsreserved.0132130807Problem:ComputingTaxes,cont.if(status==0){//Computetaxforsinglefilers}elseif(status==1){//C

omputetaxformarriedfilejointly}elseif(status==2){//Computetaxformarriedfileseparately}elseif(status==3){//Computetaxforheadofhousehold}else{

//Displaywrongstatus}28ComputeTaxRunLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807L

ogicalOperators29OperatorName!not&&and||or^exclusiveorLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011Pea

rsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator!30p!ptruefalsefalsetrueExample(assumeage=24,gender='M')!(age>18

)isfalse,because(age>18)istrue.!(gender!='F')istrue,because(grade!='F')isfalse.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEduc

ation,Inc.Allrightsreserved.0132130807TruthTableforOperator&&31p1p2p1&&p2falsefalsefalsefalsetruefalsetruefalsefalsetruetruet

rueExample(assumeage=24,gender='F')(age>18)&&(gender=='F')istrue,because(age>18)and(gender=='F')arebothtrue.(age>18)&&(gender!='F')isfals

e,because(gender!='F')isfalse.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducat

ion,Inc.Allrightsreserved.0132130807TruthTableforOperator||32p1p2p1||p2falsefalsefalsefalsetruetruetruefalsetruetrue

truetrueExample(assumeage=24,gender='F')(age>34)||(gender=='F')istrue,because(gender=='F')istrue.(age>34)||(gender=='M')isfalse,be

cause(age>34)and(gender=='M')arebothfalse.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011Pearso

nEducation,Inc.Allrightsreserved.0132130807Examples33Hereisaprogramthatcheckswhetheranumberisdivisibleby2and3,wh

etheranumberisdivisibleby2or3,andwhetheranumberisdivisibleby2or3butnotboth:TestBooleanOperatorsRunLiang,IntroductiontoJavaProgramming,

EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator!34p!ptruefalsefalsetr

ueExample!(1>2)istrue,because(1>2)isfalse.!(1>0)isfalse,because(1>0)istrue.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)201

1PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator&&35p1p2p1&&p2falsefalsefalsefalsetruefalsetr

uefalsefalsetruetruetrueExample(3>2)&&(5>=5)istrue,because(3>2)and(5>=5)arebothtrue.(3>2)&&(5>5)isfalse,becaus

e(5>5)isfalse.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.01

32130807TruthTableforOperator||36p1p2p1||p2falsefalsefalsefalsetruetruetruefalsetruetruetruetrueExample(2>3)||(5>5)isfalse,b

ecause(2>3)and(5>5)arebothfalse.(3>2)||(5>5)istrue,because(3>2)istrue.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)20

11PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator^37p1p2p1^p2falsefalsefalsefalsetruetruetruef

alsetruetruetruefalseExample(assumeage=24,gender='F')(age>34)^(gender=='F')istrue,because(age>34)isf

alsebut(gender=='F')istrue.(age>34)||(gender=='M')isfalse,because(age>34)and(gender=='M')arebothfalse.Lian

g,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Examples38System.out.prin

tln("Is"+number+"divisibleby2and3?"+((number%2==0)&&(number%3==0)));System.out.println("Is"+number+"divisibleby2or3?"+

((number%2==0)||(number%3==0)));System.out.println("Is"+number+"divisibleby2or3,butnotboth?"+((number%2==0)^(number%3==0

)));TestBooleanOperatorsRunLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrigh

tsreserved.0132130807The&and|OperatorsSupplementIII.B,“The&and|Operators”39CompanionWebsiteLiang,IntroductiontoJavaProgramming,Eig

hthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807The&and|OperatorsIfxis1,whatisxafterthisexpres

sion?(x>1)&(x++<10)Ifxis1,whatisxafterthisexpression?(1>x)&&(1>x++)Howabout(1==x)|(10>x++)?(1==x)||(10>x++)?40Compan

ionWebsiteLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Proble

m:DeterminingLeapYear?41LeapYearRunThisprogramfirstpromptstheusertoenterayearasanintvalueandchecksifitisa

leapyear.Ayearisaleapyearifitisdivisibleby4butnotby100,oritisdivisibleby400.(year%4==0&&year%100!=0)||(

year%400==0)Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Problem:LotteryWriteaprog

ramthatrandomlygeneratesalotteryofatwo-digitnumber,promptstheusertoenteratwo-digitnumber,anddetermineswhethertheuserwinsaccordingtothefollowi

ngrule:42LotteryRun•Iftheuserinputmatchesthelotteryinexactorder,theawardis$10,000.•Iftheuserinputmatchesthelottery,theawardis$3,000.•

Ifonedigitintheuserinputmatchesadigitinthelottery,theawardis$1,000.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2

011PearsonEducation,Inc.Allrightsreserved.0132130807switchStatementsswitch(status){case0:computetaxesforsinglefiler

s;break;case1:computetaxesformarriedfilejointly;break;case2:computetaxesformarriedfileseparately;break

;case3:computetaxesforheadofhousehold;break;default:System.out.println("Errors:invalidstatus");System.exit(0);}43Liang,Introdu

ctiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807switchState

mentFlowChart44statusis0ComputetaxforsinglefilersbreakComputetaxformarriedfilejointlybreakstatusis1Compute

taxformarriedfileseparatlybreakstatusis2Computetaxforheadofhouseholdbreakstatusis3DefaultactionsdefaultNextStatementLian

g,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807switchStatementRules45

switch(switch-expression){casevalue1:statement(s)1;break;casevalue2:statement(s)2;break;…casevalueN:s

tatement(s)N;break;default:statement(s)-for-default;}Theswitch-expressionmustyieldavalueofchar,byte,short,orinttypeandmustalwaysbeenclosedin

parentheses.Thevalue1,...,andvalueNmusthavethesamedatatypeasthevalueoftheswitch-expression.Theresultingstatementsinthecasestat

ementareexecutedwhenthevalueinthecasestatementmatchesthevalueoftheswitch-expression.Notethatvalue1,...,andvalueNarecon

stantexpressions,meaningthattheycannotcontainvariablesintheexpression,suchas1+x.Liang,IntroductiontoJ

avaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807switchStatementRulesThekeywordbreakisoptional,butitshouldbeus

edattheendofeachcaseinordertoterminatetheremainderoftheswitchstatement.Ifthebreakstatementisnotpresent,thenextcasestatementwillb

eexecuted.46switch(switch-expression){casevalue1:statement(s)1;break;casevalue2:statement(s)2;break;…casevalueN:sta

tement(s)N;break;default:statement(s)-for-default;}Thedefaultcase,whichisoptional,canbeusedtoperformactionswhenno

neofthespecifiedcasesmatchestheswitch-expression.Thecasestatementsareexecutedinsequentialorder,buttheorderofthecases(includingthedefaultcase)doesn

otmatter.However,itisgoodprogrammingstyletofollowthelogicalsequenceofthecasesandplacethedefaultcaseattheend

.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstatement47switch(ch){c

ase'a':System.out.println(ch);case'b':System.out.println(ch);case'c':System.out.println(ch);}Supposechis'a':animationLia

ng,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130

807Traceswitchstatement48switch(ch){case'a':System.out.println(ch);case'b':System.out.println(ch);case'c

':System.out.println(ch);}chis'a':animationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducat

ion,Inc.Allrightsreserved.0132130807Traceswitchstatement49switch(ch){case'a':System.out.println(ch);case'b':System.ou

t.println(ch);case'c':System.out.println(ch);}ExecutethislineanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011Pe

arsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstatement50switch(ch){case'a':System.out.println(ch);case'b':System.o

ut.println(ch);case'c':System.out.println(ch);}ExecutethislineanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc

.Allrightsreserved.0132130807Traceswitchstatement51switch(ch){case'a':System.out.println(ch);case'b':System.out.println(

ch);case'c':System.out.println(ch);}ExecutethislineanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)201

1PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstatement52switch(ch){case'a':System.out

.println(ch);case'b':System.out.println(ch);case'c':System.out.println(ch);}Nextstatement;ExecutenextstatementanimationLiang,IntroductiontoJavaProgra

mming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstatement53switch(ch){case'a':System.out.println(ch);break

;case'b':System.out.println(ch);break;case'c':System.out.println(ch);}Supposechis'a':animationLiang,IntroductiontoJavaPr

ogramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstatement54switch(ch){case'a':System.o

ut.println(ch);break;case'b':System.out.println(ch);break;case'c':System.out.println(ch);}chis'a':animationLiang,IntroductiontoJavaProg

ramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstatement55

switch(ch){case'a':System.out.println(ch);break;case'b':System.out.println(ch);break;case'c':System.out.println(ch);}Executethislineanimat

ionLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstatement56switc

h(ch){case'a':System.out.println(ch);break;case'b':System.out.println(ch);break;case'c':System.out.println(

ch);}ExecutethislineanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Trac

eswitchstatement57switch(ch){case'a':System.out.println(ch);break;case'b':System.out.println(ch);break;case'c':System.out.println(ch);}Nextstateme

nt;ExecutenextstatementanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsres

erved.0132130807ConditionalOperatorif(x>0)y=1elsey=-1;isequivalenttoy=(x>0)?1:-1;(boolean-expression)?expression1:expression2Ternaryopera

torBinaryoperatorUnaryoperator58Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allright

sreserved.0132130807ConditionalOperatorif(num%2==0)System.out.println(num+“iseven”);elseSystem.out.println(num+“isodd”);

System.out.println((num%2==0)?num+“iseven”:num+“isodd”);59Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011P

earsonEducation,Inc.Allrightsreserved.0132130807ConditionalOperator,cont.(boolean-expression)?exp1:exp260Liang,Introduction

toJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807FormattingOutput61Usetheprintfstatement.Sys

tem.out.printf(format,items);Whereformatisastringthatmayconsistofsubstringsandformatspecifiers.Aformatspecifiers

pecifieshowanitemshouldbedisplayed.Anitemmaybeanumericvalue,character,booleanvalue,orastring.Eachspecifierb

eginswithapercentsign.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserv

ed.0132130807Frequently-UsedSpecifiers62SpecifierOutputExample%babooleanvaluetrueorfalse%cacharacter'a'%dadecimalinte

ger200%fafloating-pointnumber45.460000%eanumberinstandardscientificnotation4.556000e+01%sastring"Javaiscool"intcount=5;doubl

eamount=45.56;System.out.printf("countis%dandamountis%f",count,amount);displaycountis5andamountis45.560000itemsLiang,IntroductiontoJa

vaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807OperatorPrecedencevar++,var--+,-(Unaryplusandmi

nus),++var,--var(type)Casting!(Not)*,/,%(Multiplication,division,andremainder)+,-(Binaryadditionandsubtraction)<,<=,>,>=(Comparison)==,!=

;(Equality)^(ExclusiveOR)&&(ConditionalAND)Short-circuitAND||(ConditionalOR)Short-circuitOR=,+=,-=,*=,/=,%=(Assignmentoper

ator)63Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserve

d.0132130807OperatorPrecedenceandAssociativityTheexpressionintheparenthesesisevaluatedfirst.(Parenthesescanbenested,inwh

ichcasetheexpressionintheinnerparenthesesisexecutedfirst.)Whenevaluatinganexpressionwithoutparentheses,theoperatorsareappliedaccordingtotheprec

edenceruleandtheassociativityrule.Ifoperatorswiththesameprecedencearenexttoeachother,theirassociativitydete

rminestheorderofevaluation.Allbinaryoperatorsexceptassignmentoperatorsareleft-associative.64Liang,IntroductiontoJavaPro

gramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807OperatorAssociativityWhentwooperatorswiththesam

eprecedenceareevaluated,theassociativityoftheoperatorsdeterminestheorderofevaluation.Allbinaryoperatorsexceptassignmentoperatorsare

left-associative.a–b+c–disequivalentto((a–b)+c)–dAssignmentoperatorsareright-associative.Therefore,theexpressiona=b+=c=5isequiv

alenttoa=(b+=(c=5))65Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.01321308

07ExampleApplyingtheoperatorprecedenceandassociativityrule,theexpression3+4*4>5*(4+3)-1isevaluatedasfollows:663+

4*4>5*(4+3)-13+4*4>5*7–13+16>5*7–13+16>35–119>35–119>34false(1)insideparenthesesfirst(2)multiplication(3)multiplication(4)additi

on(5)subtraction(6)greaterthanLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,

Inc.Allrightsreserved.0132130807CompanionWebsiteOperandEvaluationOrderSupplementIII.A,“Advanceddiscussionsonhowanexpressionisev

aluatedintheJVM.”67Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.01321308

07(GUI)ConfirmationDialogsintoption=JOptionPane.showConfirmDialog(null,"Continue");68Liang,IntroductiontoJ

avaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Problem:GuessingBirthDateTheprogramcan

guessyourbirthdate.Runtoseehowitworks.69GuessBirthDateUsingConfirmationDialogRun1617181920212223242526272829303

1Set1891011121314152425262728293031Set2135791113151719212325272931Set32367101114151819222326273031Set445671213141520

21222328293031Set5+=19

小橙橙
小橙橙
文档分享,欢迎浏览!
  • 文档 25747
  • 被下载 7
  • 被收藏 0
相关资源
广告代码123
若发现您的权益受到侵害,请立即联系客服,我们会尽快为您处理。侵权客服QQ:395972555 (支持时间:9:00-21:00) 公众号
Powered by 太赞文库
×
确认删除?