- 1.51 MB
- 2022-04-29 14:45:17 发布
- 1、本文档共5页,可阅读全部内容。
- 2、本文档内容版权归属内容提供方,所产生的收益全部归内容提供方所有。如果您对本文有版权争议,可选择认领,认领后既往收益都归您。
- 3、本文档由用户上传,本站不保证质量和数量令人满意,可能有诸多瑕疵,付费之前,请仔细先通过免费阅读内容等途径辨别内容交易风险。如存在严重挂羊头卖狗肉之情形,可联系本站下载客服投诉处理。
- 文档侵权举报电话:19940600175。
'第一页,共70页。
MotivationsIfyouassignedanegativevalueforradiusinListing2.1,ComputeArea.java,theprogramwouldprintaninvalidresult.Iftheradiusisnegative,youdon"twanttheprogramtocomputethearea.Howcanyoudealwiththissituation?2第二页,共70页。
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).3*第三页,共70页。
ThebooleanTypeandOperatorsOfteninaprogramyouneedtocomparetwovalues,suchaswhetheriisgreaterthanj.Javaprovidessixcomparisonoperators(alsoknownasrelationaloperators)thatcanbeusedtocomparetwovalues.TheresultofthecomparisonisaBooleanvalue:trueorfalse.booleanb=(1>2);4第四页,共70页。
ComparisonOperatorsOperatorNamegreaterthan>=greaterthanorequalto==equalto!=notequalto5第五页,共70页。
Problem:ASimpleMathLearningToolAdditionQuizRunThisexamplecreatesaprogramtoletafirstgraderpracticeadditions.Theprogramrandomlygeneratestwosingle-digitintegersnumber1andnumber2anddisplaysaquestionsuchas“Whatis7+9?”tothestudent.Afterthestudenttypestheanswer,theprogramdisplaysamessagetoindicatewhethertheansweristrueorfalse.6第六页,共70页。
One-wayifStatementsif(boolean-expression){statement(s);}if(radius>=0){area=radius*radius*PI;System.out.println("Thearea"+"forthecircleofradius"+radius+"is"+area);}7第七页,共70页。
Note8第八页,共70页。
SimpleifDemoSimpleIfDemoRunWriteaprogramthatpromptstheusertoenteraninteger.Ifthenumberisamultipleof5,printHiFive.Ifthenumberisdivisibleby2,printHiEven.9第九页,共70页。
Problem:GuessingBirthdayGuessBirthdayTheprogramcanguessyourbirthdate.Runtoseehowitworks.10第十页,共70页。
MathematicsBasisfortheGame19is10011inbinary.7is111inbinary.23is11101inbinary11第十一页,共70页。
TheTwo-wayifStatementif(boolean-expression){statement(s)-for-the-true-case;}else{statement(s)-for-the-false-case;}12第十二页,共70页。
if...elseExampleif(radius>=0){area=radius*radius*3.14159;System.out.println("Theareaforthe“+“circleofradius"+radius+"is"+area);}else{System.out.println("Negativeinput");}13第十三页,共70页。
MultipleAlternativeifStatements14第十四页,共70页。
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第十五页,共70页。
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第十六页,共70页。
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第十七页,共70页。
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第十八页,共70页。
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第十九页,共70页。
NoteTheelseclausematchesthemostrecentifclauseinthesameblock.20第二十页,共70页。
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第二十一页,共70页。
CommonErrorsAddingasemicolonattheendofanifclauseisacommonmistake.if(radius>=0);{area=radius*radius*PI;System.out.println("Theareaforthecircleofradius"+radius+"is"+area);}Thismistakeishardtofind,becauseitisnotacompilationerrororaruntimeerror,itisalogicerror.Thiserroroftenoccurswhenyouusethenext-lineblockstyle.Wrong22第二十二页,共70页。
TIP23第二十三页,共70页。
CAUTION24第二十四页,共70页。
Problem:AnImprovedMathLearningToolThisexamplecreatesaprogramtoteachafirstgradechildhowtolearnsubtractions.Theprogramrandomlygeneratestwosingle-digitintegersnumber1andnumber2withnumber1>number2anddisplaysaquestionsuchas“Whatis9–2?”tothestudent.Afterthestudenttypestheanswerintheinputdialogbox,theprogramdisplaysamessagedialogboxtoindicatewhethertheansweriscorrect.SubtractionQuiz25第二十五页,共70页。
Problem:BodyMassIndexBodyMassIndex(BMI)isameasureofhealthonweight.Itcanbecalculatedbytakingyourweightinkilogramsanddividingbythesquareofyourheightinmeters.TheinterpretationofBMIforpeople16yearsorolderisasfollows:ComputeBMI26第二十六页,共70页。
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第二十七页,共70页。
Problem:ComputingTaxes,cont.ComputeTaxif(status==0){//Computetaxforsinglefilers}elseif(status==1){//Computetaxformarriedfilejointly}elseif(status==2){//Computetaxformarriedfileseparately}elseif(status==3){//Computetaxforheadofhousehold}else{//Displaywrongstatus}28第二十八页,共70页。
LogicalOperatorsOperatorName!not&&and||or^exclusiveor29第二十九页,共70页。
TruthTableforOperator!30第三十页,共70页。
TruthTableforOperator&&31第三十一页,共70页。
TruthTableforOperator||32第三十二页,共70页。
ExamplesHereisaprogramthatcheckswhetheranumberisdivisibleby2and3,whetheranumberisdivisibleby2or3,andwhetheranumberisdivisibleby2or3butnotboth:TestBooleanOperatorsRun33第三十三页,共70页。
TruthTableforOperator!34第三十四页,共70页。
TruthTableforOperator&&35第三十五页,共70页。
TruthTableforOperator||36第三十六页,共70页。
TruthTableforOperator^37第三十七页,共70页。
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第三十八页,共70页。
The&and|OperatorsSupplementIII.B,“The&and|Operators”CompanionWebsite39第三十九页,共70页。
The&and|OperatorsIfxis1,whatisxafterthisexpression?(x>1)&(x++<10)Ifxis1,whatisxafterthisexpression?(1>x)&&(1>x++)Howabout(1==x)|(10>x++)?(1==x)||(10>x++)?CompanionWebsite40第四十页,共70页。
Problem:DeterminingLeapYear?LeapYearRunThisprogramfirstpromptstheusertoenterayearasanintvalueandchecksifitisaleapyear.Ayearisaleapyearifitisdivisibleby4butnotby100,oritisdivisibleby400.(year%4==0&&year%100!=0)||(year%400==0)41第四十一页,共70页。
Problem:LotteryWriteaprogramthatrandomlygeneratesalotteryofatwo-digitnumber,promptstheusertoenteratwo-digitnumber,anddetermineswhethertheuserwinsaccordingtothefollowingrule:LotteryIftheuserinputmatchesthelotteryinexactorder,theawardis$10,000.Iftheuserinputmatchesthelottery,theawardis$3,000.Ifonedigitintheuserinputmatchesadigitinthelottery,theawardis$1,000.42第四十二页,共70页。
switchStatementsswitch(status){case0:computetaxesforsinglefilers;break;case1:computetaxesformarriedfilejointly;break;case2:computetaxesformarriedfileseparately;break;case3:computetaxesforheadofhousehold;break;default:System.out.println("Errors:invalidstatus");System.exit(0);}43第四十三页,共70页。
switchStatementFlowChart44第四十四页,共70页。
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第四十五页,共70页。
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第四十六页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Supposechis"a":animation47第四十七页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}chis"a":animation48第四十八页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Executethislineanimation49第四十九页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Executethislineanimation50第五十页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Executethislineanimation51第五十一页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);case"b":System.out.println(ch);case"c":System.out.println(ch);}Nextstatement;Executenextstatementanimation52第五十二页,共70页。
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第五十三页,共70页。
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第五十四页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);break;case"b":System.out.println(ch);break;case"c":System.out.println(ch);}Executethislineanimation55第五十五页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);break;case"b":System.out.println(ch);break;case"c":System.out.println(ch);}Executethislineanimation56第五十六页,共70页。
Traceswitchstatementswitch(ch){case"a":System.out.println(ch);break;case"b":System.out.println(ch);break;case"c":System.out.println(ch);}Nextstatement;Executenextstatementanimation57第五十七页,共70页。
ConditionalOperatorif(x>0)y=1elsey=-1;isequivalenttoy=(x>0)?1:-1;(boolean-expression)?expression1:expression2TernaryoperatorBinaryoperatorUnaryoperator58第五十八页,共70页。
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第五十九页,共70页。
ConditionalOperator,cont.(boolean-expression)?exp1:exp260第六十页,共70页。
FormattingOutputUsetheprintfstatement.System.out.printf(format,items);Whereformatisastringthatmayconsistofsubstringsandformatspecifiers.Aformatspecifierspecifieshowanitemshouldbedisplayed.Anitemmaybeanumericvalue,character,booleanvalue,orastring.Eachspecifierbeginswithapercentsign.61第六十一页,共70页。
Frequently-UsedSpecifiersSpecifierOutputExample%babooleanvaluetrueorfalse%cacharacter"a"%dadecimalinteger200%fafloating-pointnumber45.460000%eanumberinstandardscientificnotation4.556000e+01%sastring"Javaiscool"62第六十二页,共70页。
OperatorPrecedencevar++,var--+,-(Unaryplusandminus),++var,--var(type)Casting!(Not)*,/,%(Multiplication,division,andremainder)+,-(Binaryadditionandsubtraction)<,<=,>,>=(Comparison)==,!=;(Equality)^(ExclusiveOR)&&(ConditionalAND)Short-circuitAND||(ConditionalOR)Short-circuitOR=,+=,-=,*=,/=,%=(Assignmentoperator)63第六十三页,共70页。
OperatorPrecedenceandAssociativityTheexpressionintheparenthesesisevaluatedfirst.(Parenthesescanbenested,inwhichcasetheexpressionintheinnerparenthesesisexecutedfirst.)Whenevaluatinganexpressionwithoutparentheses,theoperatorsareappliedaccordingtotheprecedenceruleandtheassociativityrule.Ifoperatorswiththesameprecedencearenexttoeachother,theirassociativitydeterminestheorderofevaluation.Allbinaryoperatorsexceptassignmentoperatorsareleft-associative.64第六十四页,共70页。
OperatorAssociativityWhentwooperatorswiththesameprecedenceareevaluated,theassociativityoftheoperatorsdeterminestheorderofevaluation.Allbinaryoperatorsexceptassignmentoperatorsareleft-associative.a–b+c–disequivalentto ((a–b)+c)–dAssignmentoperatorsareright-associative.Therefore,theexpressiona=b+=c=5isequivalenttoa=(b+=(c=5))65第六十五页,共70页。
ExampleApplyingtheoperatorprecedenceandassociativityrule,theexpression3+4*4>5*(4+3)-1isevaluatedasfollows:66第六十六页,共70页。
OperandEvaluationOrderSupplementIII.A,“AdvanceddiscussionsonhowanexpressionisevaluatedintheJVM.”CompanionWebsite67第六十七页,共70页。
(GUI)ConfirmationDialogsintoption=JOptionPane.showConfirmDialog(null,"Continue");68第六十八页,共70页。
Problem:GuessingBirthDateGuessBirthDateUsingConfirmationDialogTheprogramcanguessyourbirthdate.Runtoseehowitworks.69第六十九页,共70页。
第七十页,共70页。'
您可能关注的文档
- 【精品】10产品策略课件PPT课件汇编
- 【精品】11.一块奶酪-课件PPT课件汇编
- 【精品】9Multisim在高频电路中的应用课件PPT课件
- 【精品】C--原子核的组成课件PPT课件
- 【精品】CAD阵列公开课课件PPT课件
- 【精品】Chap009-资本资产定价模型兹维-博迪-《投资学-》第九版课件PPTPPT课件
- 【精品】Chap010-套利定价理论与风险收益多因素模型兹维-博迪-《投资学-》第九版课件PPT教学资料
- 【精品】DNA是主要的遗传物质半成品课件PPT课件精品课件
- 【精品】ICU-CSPEN课件PPT课件精品课件
- 【精品】PEP小学英语三年级下册-Unit-2-My-family-Part-B-Let’s-talk课件PPT课件精品课件
- 【精品】pep英语五年级下unit2my-favourite-seasonPPT课件PPT课件精品课件
- 【精品】S版五年级语文上册《天窗》课件PPT课件精品课件
- 【精品】unit-1-Festivals-around-the-world课件PPT课件精品课件
- 【精品】Unit-1-Hello!-课件PPT课件精品课件
- 【精品】●脚手架安全施工培训课件PPT课件精品课件
- 【精品】《CT质量控制》PPT课件PPT课件精品课件
- 【精品】《一次函数的图象和性质》课件PPT课件精品课件
- 【精品】《七颗钻石》课件PPT课件精品课件