- 403.00 KB
- 2022-04-29 14:36:07 发布
- 1、本文档共5页,可阅读全部内容。
- 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
- 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
- 文档侵权举报电话:19940600175。
'Chapter3Selections1Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807
MotivationsIfyouassignedanegativevalueforradiusinListing2.1,ComputeArea.java,theprogramwouldprintaninvalidresult.Iftheradiusisnegative,youdon"twanttheprogramtocomputethearea.Howcanyoudealwiththissituation?2
ObjectivesTodeclarebooleantypeandwriteBooleanexpressionsusingcomparisonoperators(§3.2).ToprogramAdditionQuizusingBooleanexpressions(§3.3).Toimplementselectioncontrolusingone-wayifstatements(§3.4)ToprogramtheGuessBirthdaygameusingone-wayifstatements(§3.5).Toimplementselectioncontrolusingtwo-wayifstatements(§3.6).Toimplementselectioncontrolusingnestedifstatements(§3.7).Toavoidcommonerrorsinifstatements(§3.8).Toprogramusingselectionstatementsforavarietyofexamples(BMI,ComputeTax,SubtractionQuiz)(§3.9-3.11).TogeneraterandomnumbersusingtheMath.random()method(§3.9).Tocombineconditionsusinglogicaloperators(&&,||,and!)(§3.12).Toprogramusingselectionstatementswithcombinedconditions(LeapYear,Lottery)(§§3.13-3.14).Toimplementselectioncontrolusingswitchstatements(§3.15).Towriteexpressionsusingtheconditionaloperator(§3.16).ToformatoutputusingtheSystem.out.printfmethodandtoformatstringsusingtheString.formatmethod(§3.17).Toexaminetherulesgoverningoperatorprecedenceandassociativity(§3.18).(GUI)Togetuserconfirmationusingconfirmationdialogs(§3.19).3Liang,IntroductiontoJavaProgramming,EighthEdition,(c)2011PearsonEducation,Inc.Allrightsreserved.0132130807
ThebooleanTypeandOperatorsOfteninaprogramyouneedtocomparetwovalues,suchaswhetheriisgreaterthanj.Javaprovidessixcomparisonoperators(alsoknownasrelationaloperators)thatcanbeusedtocomparetwovalues.TheresultofthecomparisonisaBooleanvalue:trueorfalse.booleanb=(1>2);4
ComparisonOperatorsOperatorNamegreaterthan>=greaterthanorequalto==equalto!=notequalto5
Problem:ASimpleMathLearningToolAdditionQuizRunThisexamplecreatesaprogramtoletafirstgraderpracticeadditions.Theprogramrandomlygeneratestwosingle-digitintegersnumber1andnumber2anddisplaysaquestionsuchas“Whatis7+9?”tothestudent.Afterthestudenttypestheanswer,theprogramdisplaysamessagetoindicatewhethertheansweristrueorfalse.6
One-wayifStatementsif(boolean-expression){statement(s);}if(radius>=0){area=radius*radius*PI;System.out.println("Thearea"+"forthecircleofradius"+radius+"is"+area);}7
Note8
SimpleifDemoSimpleIfDemoRunWriteaprogramthatpromptstheusertoenteraninteger.Ifthenumberisamultipleof5,printHiFive.Ifthenumberisdivisibleby2,printHiEven.9
Problem:GuessingBirthdayGuessBirthdayTheprogramcanguessyourbirthdate.Runtoseehowitworks.10
MathematicsBasisfortheGame19is10011inbinary.7is111inbinary.23is11101inbinary11
TheTwo-wayifStatementif(boolean-expression){statement(s)-for-the-true-case;}else{statement(s)-for-the-false-case;}12
if...elseExampleif(radius>=0){area=radius*radius*3.14159;System.out.println("Theareaforthe“+“circleofradius"+radius+"is"+area);}else{System.out.println("Negativeinput");}13
MultipleAlternativeifStatements14
Traceif-elsestatementif(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.0Theconditionisfalseanimation15
Traceif-elsestatementif(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.0Theconditionisfalseanimation16
Traceif-elsestatementif(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.0Theconditionistrueanimation17
Traceif-elsestatementif(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.0gradeisCanimation18
Traceif-elsestatementif(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.0Exittheifstatementanimation19
NoteTheelseclausematchesthemostrecentifclauseinthesameblock.20
Note,cont.Nothingisprintedfromtheprecedingstatement.Toforcetheelseclausetomatchthefirstifclause,youmustaddapairofbraces:inti=1;intj=2;intk=3;if(i>j){if(i>k)System.out.println("A");}elseSystem.out.println("B");ThisstatementprintsB.21
CommonErrorsAddingasemicolonattheendofanifclauseisacommonmistake.if(radius>=0);{area=radius*radius*PI;System.out.println("Theareaforthecircleofradius"+radius+"is"+area);}Thismistakeishardtofind,becauseitisnotacompilationerrororaruntimeerror,itisalogicerror.Thiserroroftenoccurswhenyouusethenext-lineblockstyle.Wrong22
TIP23
CAUTION24
Problem:AnImprovedMathLearningToolThisexamplecreatesaprogramtoteachafirstgradechildhowtolearnsubtractions.Theprogramrandomlygeneratestwosingle-digitintegersnumber1andnumber2withnumber1>number2anddisplaysaquestionsuchas“Whatis9–2?”tothestudent.Afterthestudenttypestheanswerintheinputdialogbox,theprogramdisplaysamessagedialogboxtoindicatewhethertheansweriscorrect.SubtractionQuiz25
Problem:BodyMassIndexBodyMassIndex(BMI)isameasureofhealthonweight.Itcanbecalculatedbytakingyourweightinkilogramsanddividingbythesquareofyourheightinmeters.TheinterpretationofBMIforpeople16yearsorolderisasfollows:ComputeBMI26
Problem:ComputingTaxesTheUSfederalpersonalincometaxiscalculatedbasedonthefilingstatusandtaxableincome.Therearefourfilingstatuses:singlefilers,marriedfilingjointly,marriedfilingseparately,andheadofhousehold.Thetaxratesfor2009areshownbelow.MarginalTaxRateSingleMarriedFilingJointlyorQualifiedWidow(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,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$190,201-$372,95035%$372,951+$372,951+$186,476+$372,951+27
Problem:ComputingTaxes,cont.ComputeTaxif(status==0){//Computetaxforsinglefilers}elseif(status==1){//Computetaxformarriedfilejointly}elseif(status==2){//Computetaxformarriedfileseparately}elseif(status==3){//Computetaxforheadofhousehold}else{//Displaywrongstatus}28
LogicalOperatorsOperatorName!not&&and||or^exclusiveor29
TruthTableforOperator!30
TruthTableforOperator&&31
TruthTableforOperator||32
ExamplesHereisaprogramthatcheckswhetheranumberisdivisibleby2and3,whetheranumberisdivisibleby2or3,andwhetheranumberisdivisibleby2or3butnotboth:TestBooleanOperatorsRun33
TruthTableforOperator!34
TruthTableforOperator&&35
TruthTableforOperator||36
TruthTableforOperator^37
ExamplesSystem.out.println("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)));TestBooleanOperatorsRun38
The&and|OperatorsSupplementIII.B,“The&and|Operators”CompanionWebsite39
The&and|OperatorsIfxis1,whatisxafterthisexpression?(x>1)&(x++<10)Ifxis1,whatisxafterthisexpression?(1>x)&&(1>x++)Howabout(1==x)|(10>x++)?(1==x)||(10>x++)?CompanionWebsite40
Problem:DeterminingLeapYear?LeapYearRunThisprogramfirstpromptstheusertoenterayearasanintvalueandchecksifitisaleapyear.Ayearisaleapyearifitisdivisibleby4butnotby100,oritisdivisibleby400.(year%4==0&&year%100!=0)||(year%400==0)41
Problem:LotteryWriteaprogramthatrandomlygeneratesalotteryofatwo-digitnumber,promptstheusertoenteratwo-digitnumber,anddetermineswhethertheuserwinsaccordingtothefollowingrule:LotteryIftheuserinputmatchesthelotteryinexactorder,theawardis$10,000.Iftheuserinputmatchesthelottery,theawardis$3,000.Ifonedigitintheuserinputmatchesadigitinthelottery,theawardis$1,000.42
switchStatementsswitch(status){case0:computetaxesforsinglefilers;break;case1:computetaxesformarriedfilejointly;break;case2:computetaxesformarriedfileseparately;break;case3:computetaxesforheadofhousehold;break;default:System.out.println("Errors:invalidstatus");System.exit(0);}43
switchStatementFlowChart44
switchStatementRulesswitch(switch-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,orinttypeandmustalwaysbeenclosedinparentheses.Thevalue1,...,andvalueNmusthavethesamedatatypeasthevalueoftheswitch-expression.Theresultingstatementsinthecasestatementareexecutedwhenthevalueinthecasestatementmatchesthevalueoftheswitch-expression.Notethatvalue1,...,andvalueNareconstantexpressions,meaningthattheycannotcontainvariablesintheexpression,suchas1+x.45
switchStatementRulesThekeywordbreakisoptional,butitshouldbeusedattheendofeachcaseinordertoterminatetheremainderoftheswitchstatement.Ifthebreakstatementisnotpresent,thenextcasestatementwillbeexecuted.switch(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.Thecasestatementsareexecutedinsequentialorder,buttheorderofthecases(includingthedefaultcase)doesnotmatter.However,itisgoodprogrammingstyletofollowthelogicalsequenceofthecasesandplacethedefaultcaseattheend.46
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Supposechis"a":animation47
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}chis"a":animation48
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Executethislineanimation49
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Executethislineanimation50
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Executethislineanimation51
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Nextstatement;Executenextstatementanimation52
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);break;case"b":System.out.println(ch);break;case"c":System.out.println(ch);}Supposechis"a":animation53
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);break;case"b":System.out.println(ch);break;case"c":System.out.println(ch);}chis"a":animation54
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);break;case"b":System.out.println(ch);break;case"c":System.out.println(ch);}Executethislineanimation55
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);break;case"b":System.out.println(ch);break;case"c":System.out.println(ch);}Executethislineanimation56
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);break;case"b":System.out.println(ch);break;case"c":System.out.println(ch);}Nextstatement;Executenextstatementanimation57
ConditionalOperatorif(x>0)y=1elsey=-1;isequivalenttoy=(x>0)?1:-1;(boolean-expression)?expression1:expression2TernaryoperatorBinaryoperatorUnaryoperator58
ConditionalOperatorif(num%2==0)System.out.println(num+“iseven”);elseSystem.out.println(num+“isodd”);System.out.println((num%2==0)?num+“iseven”:num+“isodd”);59
ConditionalOperator,cont.(boolean-expression)?exp1:exp260
FormattingOutputUsetheprintfstatement.System.out.printf(format,items);Whereformatisastringthatmayconsistofsubstringsandformatspecifiers.Aformatspecifierspecifieshowanitemshouldbedisplayed.Anitemmaybeanumericvalue,character,booleanvalue,orastring.Eachspecifierbeginswithapercentsign.61
Frequently-UsedSpecifiersSpecifierOutputExample%babooleanvaluetrueorfalse%cacharacter"a"%dadecimalinteger200%fafloating-pointnumber45.460000%eanumberinstandardscientificnotation4.556000e+01%sastring"Javaiscool"62
OperatorPrecedencevar++,var--+,-(Unaryplusandminus),++var,--var(type)Casting!(Not)*,/,%(Multiplication,division,andremainder)+,-(Binaryadditionandsubtraction)<,<=,>,>=(Comparison)==,!=;(Equality)^(ExclusiveOR)&&(ConditionalAND)Short-circuitAND||(ConditionalOR)Short-circuitOR=,+=,-=,*=,/=,%=(Assignmentoperator)63
OperatorPrecedenceandAssociativityTheexpressionintheparenthesesisevaluatedfirst.(Parenthesescanbenested,inwhichcasetheexpressionintheinnerparenthesesisexecutedfirst.)Whenevaluatinganexpressionwithoutparentheses,theoperatorsareappliedaccordingtotheprecedenceruleandtheassociativityrule.Ifoperatorswiththesameprecedencearenexttoeachother,theirassociativitydeterminestheorderofevaluation.Allbinaryoperatorsexceptassignmentoperatorsareleft-associative.64
OperatorAssociativityWhentwooperatorswiththesameprecedenceareevaluated,theassociativityoftheoperatorsdeterminestheorderofevaluation.Allbinaryoperatorsexceptassignmentoperatorsareleft-associative.a–b+c–disequivalentto ((a–b)+c)–dAssignmentoperatorsareright-associative.Therefore,theexpressiona=b+=c=5isequivalenttoa=(b+=(c=5))65
ExampleApplyingtheoperatorprecedenceandassociativityrule,theexpression3+4*4>5*(4+3)-1isevaluatedasfollows:66
OperandEvaluationOrderSupplementIII.A,“AdvanceddiscussionsonhowanexpressionisevaluatedintheJVM.”CompanionWebsite67
(GUI)ConfirmationDialogsintoption=JOptionPane.showConfirmDialog(null,"Continue");68
Problem:GuessingBirthDateGuessBirthDateUsingConfirmationDialogTheprogramcanguessyourbirthdate.Runtoseehowitworks.69'
您可能关注的文档
- 一年级《找规律》课件PPT.ppt
- 人教版六年级数学下册《解比例》课件PPT.ppt
- 内能优秀课件PPT.ppt
- 勾股定理课件PPT.ppt
- 人教版八年级下册《海燕》教学课件PPT.ppt
- 幼儿园小班课件PPT-认识形状.ppt
- (合肥一中获奖课件)高一物理摩擦力课件PPT(新课标).ppt
- 《望庐山瀑布》课件PPT.ppt
- C语言程序设计教程课件PPT.ppt
- 胆囊结石护理查房课件PPT123.ppt
- 电子测量技术基础课件PPT6频域测量.ppt
- 电磁场与电磁波理论课件PPT第2章.ppt
- 高三第一轮《机械能》复习课件PPT.ppt
- 高中生物必修一-第三章--细胞的基本结构-第三节细胞核——系统的控制中心-说课课件PPT.ppt
- 机械制图课件PPT-第三章.ppt
- 机械制造工艺基础课件PPT-第1章--金属切削的基础知识.ppt
- 小学语文一年级上册汉语拼音1 a o e 教学课件PPT课件.ppt
- 六年级语文下册18《跨越百年的美丽》课件PPT.ppt