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

PPT
  • 阅读 132 次
  • 下载 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.0132130807Chapter3Selections1Liang,Introduct

iontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807MotivationsIfyouassignedanegativevalue

forradiusinListing2.1,ComputeArea.java,theprogramwouldprintaninvalidresult.Iftheradiusisnegative,youdon'twanttheprogram

tocomputethearea.Howcanyoudealwiththissituation?2Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation

,Inc.Allrightsreserved.0132130807Objectives3TodeclarebooleantypeandwriteBooleanexpressionsusingcomparisonoperato

rs(§3.2).ToprogramAdditionQuizusingBooleanexpressions(§3.3).Toimplementselectioncontrolusingone-wayifstatements(§3.4)ToprogramtheGuessBi

rthdaygameusingone-wayifstatements(§3.5).Toimplementselectioncontrolusingtwo-wayifstatements(§3.6).Toimplementselectioncontrol

usingnestedifstatements(§3.7).Toavoidcommonerrorsinifstatements(§3.8).Toprogramusingselectionstatemen

tsforavarietyofexamples(BMI,ComputeTax,SubtractionQuiz)(§3.9-3.11).TogeneraterandomnumbersusingtheMath.random()method(§3.9).Tocomb

ineconditionsusinglogicaloperators(&&,||,and!)(§3.12).Toprogramusingselectionstatementswithcombinedconditi

ons(LeapYear,Lottery)(§§3.13-3.14).Toimplementselectioncontrolusingswitchstatements(§3.15).Towriteexpressionsusingtheco

nditionaloperator(§3.16).ToformatoutputusingtheSystem.out.printfmethodandtoformatstringsusingtheString.formatm

ethod(§3.17).Toexaminetherulesgoverningoperatorprecedenceandassociativity(§3.18).(GUI)Togetuserconfirmationusingco

nfirmationdialogs(§3.19).Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Thebo

oleanTypeandOperatorsOfteninaprogramyouneedtocomparetwovalues,suchaswhetheriisgreaterthanj.Javaprovidessixcomparisonoperators(alsoknownasrela

tionaloperators)thatcanbeusedtocomparetwovalues.TheresultofthecomparisonisaBooleanvalue:trueorfalse.boo

leanb=(1>2);4Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807ComparisonOperators5OperatorN

ame<lessthan<=lessthanorequalto>greaterthan>=greaterthanorequalto==equalto!=notequaltoLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011Pe

arsonEducation,Inc.Allrightsreserved.0132130807Problem:ASimpleMathLearningTool6AdditionQuizRunThisexamplecrea

tesaprogramtoletafirstgraderpracticeadditions.Theprogramrandomlygeneratestwosingle-digitintegersnumber1andnumber2anddisplaysaqu

estionsuchas“Whatis7+9?”tothestudent.Afterthestudenttypestheanswer,theprogramdisplaysamessagetoindicatewhethertheansweri

strueorfalse.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807One-wayifState

mentsif(boolean-expression){statement(s);}7BooleanExpressiontrueStatement(s)false(radius>=0)truearea=radius*radi

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

n("Thearea"+"forthecircleofradius"+radius+"is"+area);}Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducati

on,Inc.Allrightsreserved.0132130807Note8ifi>0{System.out.println("iispositive");}(a)Wrong(b)Correctif(i>0){System.out.println("iispositive

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

thEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807SimpleifDemo9SimpleIfDemoRunWriteaprogramthatpromptstheusertoent

eraninteger.Ifthenumberisamultipleof5,printHiFive.Ifthenumberisdivisibleby2,printHiEven.Liang,IntroductiontoJavaP

rogramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Problem:GuessingBirthdayTheprogramcan

guessyourbirthdate.Runtoseehowitworks.10GuessBirthdayRun16171819202122232425262728293031Set18910111213141524

25262728293031Set2135791113151719212325272931Set32367101114151819222326273031Set44567121314152021222328293031Set5+=19Liang,IntroductiontoJavaProgram

ming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807MathematicsBasisfortheGame19is10011inbinary.7is111inbinary.23is11101inbi

nary1116171819202122232425262728293031Set1891011121314152425262728293031Set2135791113151719212325272931Set323671011141

51819222326273031Set44567121314152021222328293031Set5+=191000010+1100110011010+100111197100001000100+1111012

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

130807TheTwo-wayifStatementif(boolean-expression){statement(s)-for-the-true-case;}else{statement(s)-for-the-false-case;}12BooleanExpressionfalsetrue

Statement(s)forthefalsecaseStatement(s)forthetruecaseLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducati

on,Inc.Allrightsreserved.0132130807if...elseExampleif(radius>=0){area=radius*radius*3.14159;System.out.println("Theareaforthe“+“circleofradius"

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

earsonEducation,Inc.Allrightsreserved.0132130807MultipleAlternativeifStatements14if(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';Equivalentif(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';Liang

,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceif-elsestat

ement15if(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.0TheconditionisfalseanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Al

lrightsreserved.0132130807Traceif-elsestatement16if(score>=90.0)grade='A';elseif(score>=80.0)grade='B';elseif(score>=70.0)grade='C';els

eif(score>=60.0)grade='D';elsegrade='F';Supposescoreis70.0TheconditionisfalseanimationLiang,IntroductiontoJavaPro

gramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceif-elsestatement17if(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';Sup

posescoreis70.0TheconditionistrueanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsres

erved.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,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEduca

tion,Inc.Allrightsreserved.0132130807Traceif-elsestatement19if(score>=90.0)grade='A';elseif(score>=80.0)grade='B';elseif(sc

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

,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.013213080

7NoteTheelseclausematchesthemostrecentifclauseinthesameblock.20inti=1;intj=2;intk=3;if(i>j)if(i>k)System.out.println("A");elseSys

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

troductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Note,cont.Nothingispri

ntedfromtheprecedingstatement.Toforcetheelseclausetomatchthefirstifclause,youmustaddapairofbraces:inti=1;intj=2;

intk=3;if(i>j){if(i>k)System.out.println("A");}elseSystem.out.println("B");ThisstatementprintsB.21Liang,IntroductiontoJava

Programming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807CommonErrorsAddingasemicolonattheendofanifclauseisacommonmistake.

if(radius>=0);{area=radius*radius*PI;System.out.println("Theareaforthecircleofradius"+radius+"is"+area);}Thismistakeishardtofind,becauseitisnotacom

pilationerrororaruntimeerror,itisalogicerror.Thiserroroftenoccurswhenyouusethenext-lineblockstyle.22WrongLiang,Introductionto

JavaProgramming,EighthEdition,(c)2011PearsonEducation,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,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEd

ucation,Inc.Allrightsreserved.0132130807Problem:AnImprovedMathLearningToolThisexamplecreatesaprogramtoteachafirstgradechildho

wtolearnsubtractions.Theprogramrandomlygeneratestwosingle-digitintegersnumber1andnumber2withnumber1>number2anddisplaysaquestionsuchas“Wha

tis9–2?”tothestudent.Afterthestudenttypestheanswerintheinputdialogbox,theprogramdisplaysamessagedialogboxtoindi

catewhethertheansweriscorrect.25SubtractionQuizRunLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.

0132130807Problem:BodyMassIndexBodyMassIndex(BMI)isameasureofhealthonweight.Itcanbecalculatedbytakingyourwei

ghtinkilogramsanddividingbythesquareofyourheightinmeters.TheinterpretationofBMIforpeople16yearsorolderisasfol

lows:26ComputeBMIRunBMIInterpretationbelow16seriousunderweight16-18underweight18-24normalweight24-29overweight29-35seriouslyoverweightab

ove35gravelyoverweightLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Pro

blem:ComputingTaxesTheUSfederalpersonalincometaxiscalculatedbasedonthefilingstatusandtaxableincome.Therearefourfilingstatuses:singlefilers,married

filingjointly,marriedfilingseparately,andheadofhousehold.Thetaxratesfor2009areshownbelow.27MarginalTaxRateSing

leMarriedFilingJointlyorQualifiedWidow(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,52

5$45,501–$117,45028%$82,251–$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$1

90,201-$372,95035%$372,951+$372,951+$186,476+$372,951+Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011Pear

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

Computetaxformarriedfilejointly}elseif(status==2){//Computetaxformarriedfileseparately}elseif(status==3){//Computetaxforheadofhousehold}e

lse{//Displaywrongstatus}28ComputeTaxRunLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEduca

tion,Inc.Allrightsreserved.0132130807LogicalOperators29OperatorName!not&&and||or^exclusiveorLiang,IntroductiontoJavaProgra

mming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator!30p!ptruefalsefalsetrueExamp

le(assumeage=24,gender='M')!(age>18)isfalse,because(age>18)istrue.!(gender!='F')istrue,because(grade!='F')isfalse.Liang,Introductiont

oJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator&&31p1p2p1&&p2falsefalsefalsefalsetruef

alsetruefalsefalsetruetruetrueExample(assumeage=24,gender='F')(age>18)&&(gender=='F')istrue,because(a

ge>18)and(gender=='F')arebothtrue.(age>18)&&(gender!='F')isfalse,because(gender!='F')isfalse.Liang,IntroductiontoJavaProgramming,EighthEd

ition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator||32p1p2p1||p2falsefalsefalsefalsetruetru

etruefalsetruetruetruetrueExample(assumeage=24,gender='F')(age>34)||(gender=='F')istrue,because(gender=='F')istrue.(age>34)||(g

ender=='M')isfalse,because(age>34)and(gender=='M')arebothfalse.Liang,IntroductiontoJavaProgramming,EighthEditio

n,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Examples33Hereisaprogramthatcheckswhetheranumberisdivisibleby2and3,whetheranumberisd

ivisibleby2or3,andwhetheranumberisdivisibleby2or3butnotboth:TestBooleanOperatorsRunLiang,IntroductiontoJavaPr

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

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

2011PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator&&35p1p2p1&&p2falsefalsefalsefalsetruefalsetruefalsef

alsetruetruetrueExample(3>2)&&(5>=5)istrue,because(3>2)and(5>=5)arebothtrue.(3>2)&&(5>5)isfalse,because(5>5)isfalse.Liang,IntroductiontoJavaProgramm

ing,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator||36p1p2p1||p2falsefalsefalsefalsetr

uetruetruefalsetruetruetruetrueExample(2>3)||(5>5)isfalse,because(2>3)and(5>5)arebothfalse.(3>2)||(5>5)istrue,because(3>2)istrue.Liang,I

ntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807TruthTableforOperator^37p1p

2p1^p2falsefalsefalsefalsetruetruetruefalsetruetruetruefalseExample(assumeage=24,gender='F')(age>34)^(gender=='F')

istrue,because(age>34)isfalsebut(gender=='F')istrue.(age>34)||(gender=='M')isfalse,because(age>34)and(gender=='M')arebothfalse.Liang,Intro

ductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Examples38System.out.println("Is"+number+"d

ivisibleby2and3?"+((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.Allrightsreserved.0132130807The&and|OperatorsSupplementIII.

B,“The&and|Operators”39CompanionWebsiteLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducati

on,Inc.Allrightsreserved.0132130807The&and|OperatorsIfxis1,whatisxafterthisexpression?(x>1)&(x++<10)Ifxis1,whatisxafte

rthisexpression?(1>x)&&(1>x++)Howabout(1==x)|(10>x++)?(1==x)||(10>x++)?40CompanionWebsiteLiang,IntroductiontoJavaP

rogramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Problem:DeterminingLeapYear?41LeapYearRunThisprogramfirs

tpromptstheusertoenterayearasanintvalueandchecksifitisaleapyear.Ayearisaleapyearifitisdivisibleby4butnotby100,oritisdivisi

bleby400.(year%4==0&&year%100!=0)||(year%400==0)Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.013

2130807Problem:LotteryWriteaprogramthatrandomlygeneratesalotteryofatwo-digitnumber,promptstheusertoenteratwo

-digitnumber,anddetermineswhethertheuserwinsaccordingtothefollowingrule:42LotteryRun•Iftheuserinputmatchesthelotteryinexactorder,theawardis$10,0

00.•Iftheuserinputmatchesthelottery,theawardis$3,000.•Ifonedigitintheuserinputmatchesadigitinthelottery,theawa

rdis$1,000.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807switchStatementsswitch(sta

tus){case0:computetaxesforsinglefilers;break;case1:computetaxesformarriedfilejointly;break;case2:computetaxesformarriedfileseparately

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

ang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807switch

StatementFlowChart44statusis0ComputetaxforsinglefilersbreakComputetaxformarriedfilejointlybreakstatusis1Comput

etaxformarriedfileseparatlybreakstatusis2Computetaxforheadofhouseholdbreakstatusis3DefaultactionsdefaultNextStatementLiang,IntroductiontoJavaProgr

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

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

(s)-for-default;}Theswitch-expressionmustyieldavalueofchar,byte,short,orinttypeandmustalwaysbeenclosedinpar

entheses.Thevalue1,...,andvalueNmusthavethesamedatatypeasthevalueoftheswitch-expression.Theresultingstatementsinthecasestatementareexecutedwhenthe

valueinthecasestatementmatchesthevalueoftheswitch-expression.Notethatvalue1,...,andvalueNareconstantexpressions,meaningthattheyca

nnotcontainvariablesintheexpression,suchas1+x.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonE

ducation,Inc.Allrightsreserved.0132130807switchStatementRulesThekeywordbreakisoptional,butitshouldbeusedattheendofeachcasein

ordertoterminatetheremainderoftheswitchstatement.Ifthebreakstatementisnotpresent,thenextcasestatementwillbeexecuted.46switch

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

;}Thedefaultcase,whichisoptional,canbeusedtoperformactionswhennoneofthespecifiedcasesmatchestheswitch-expression.Thecasestatementsareexecut

edinsequentialorder,buttheorderofthecases(includingthedefaultcase)doesnotmatter.However,itisgoodprogrammingstyletofollowthelogicalsequenceofthe

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

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

System.out.println(ch);}Supposechis'a':animationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0

132130807Traceswitchstatement48switch(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)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstatement

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

ethislineanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstat

ement50switch(ch){case'a':System.out.println(ch);case'b':System.out.println(ch);case'c':System.out.println(ch);}Exe

cutethislineanimationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitchstateme

nt51switch(ch){case'a':System.out.println(ch);case'b':System.out.println(ch);case'c':System.out.println(ch);}ExecutethislineanimationLiang,I

ntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Traceswitch

statement52switch(ch){case'a':System.out.println(ch);case'b':System.out.println(ch);case'c':System.out.println(ch);}Nextstatement;Executenextstatem

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

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

ntln(ch);}Supposechis'a':animationLiang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0

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

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

ightsreserved.0132130807Traceswitchstatement55switch(ch){case'a':System.out.println(ch);break;case'b':System.out.println(ch);br

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

cation,Inc.Allrightsreserved.0132130807Traceswitchstatement56switch(ch){case'a':System.out.println(ch);break;case'b':System.out.println(c

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

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

(ch);break;case'b':System.out.println(ch);break;case'c':System.out.println(ch);}Nextstatement;ExecutenextstatementanimationL

iang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807C

onditionalOperatorif(x>0)y=1elsey=-1;isequivalenttoy=(x>0)?1:-1;(boolean-expression)?expression1:expression2TernaryoperatorBin

aryoperatorUnaryoperator58Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,In

c.Allrightsreserved.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,EighthEditio

n,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807ConditionalOperator,cont.(boolean-expression)?exp1:

exp260Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807FormattingO

utput61Usetheprintfstatement.System.out.printf(format,items);Whereformatisastringthatmayconsistofsub

stringsandformatspecifiers.Aformatspecifierspecifieshowanitemshouldbedisplayed.Anitemmaybeanumericvalue,character,booleanvalue

,orastring.Eachspecifierbeginswithapercentsign.Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducat

ion,Inc.Allrightsreserved.0132130807Frequently-UsedSpecifiers62SpecifierOutputExample%babooleanvaluetrueorfalse%cacharacter'a'%dadec

imalinteger200%fafloating-pointnumber45.460000%eanumberinstandardscientificnotation4.556000e+01%sastring"Javai

scool"intcount=5;doubleamount=45.56;System.out.printf("countis%dandamountis%f",count,amount);displaycountis5andamountis45.560000itemsLiang,Intro

ductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807OperatorPr

ecedencevar++,var--+,-(Unaryplusandminus),++var,--var(type)Casting!(Not)*,/,%(Multiplication,div

ision,andremainder)+,-(Binaryadditionandsubtraction)<,<=,>,>=(Comparison)==,!=;(Equality)^(ExclusiveOR)&&(ConditionalAND)Short-circuitAND

||(ConditionalOR)Short-circuitOR=,+=,-=,*=,/=,%=(Assignmentoperator)63Liang,IntroductiontoJavaProg

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

ityTheexpressionintheparenthesesisevaluatedfirst.(Parenthesescanbenested,inwhichcasetheexpressionintheinnerparenthesesisexecutedfirst.

)Whenevaluatinganexpressionwithoutparentheses,theoperatorsareappliedaccordingtotheprecedenceruleandtheassociativityrule.Ifoperatorswiththesamepr

ecedencearenexttoeachother,theirassociativitydeterminestheorderofevaluation.Allbinaryoperatorsexceptassignmentoperatorsa

releft-associative.64Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrigh

tsreserved.0132130807OperatorAssociativityWhentwooperatorswiththesameprecedenceareevaluated,theassociativityofthe

operatorsdeterminestheorderofevaluation.Allbinaryoperatorsexceptassignmentoperatorsareleft-associative.a–b+c–

disequivalentto((a–b)+c)–dAssignmentoperatorsareright-associative.Therefore,theexpressiona=b+=c=5isequivalenttoa=(b+=(c=5))65L

iang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807ExampleApplyingtheop

eratorprecedenceandassociativityrule,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)addition(5)subtraction(6)greaterthanLiang,IntroductiontoJavaProgra

mming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807CompanionWebsiteOperandEvaluationOrderSupplementIII.A,“Advanceddis

cussionsonhowanexpressionisevaluatedintheJVM.”67Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,

Inc.Allrightsreserved.0132130807(GUI)ConfirmationDialogsintoption=JOptionPane.showConfirmDialog(null,"Continue");68Liang,IntroductiontoJavaPr

ogramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807Problem:GuessingBirthDateTheprogramcangu

essyourbirthdate.Runtoseehowitworks.69GuessBirthDateUsingConfirmationDialogRun16171819202122232425262728293031Set1891011121314152425262728293031

Set2135791113151719212325272931Set32367101114151819222326273031Set44567121314152021222328293031Set5+=19

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