已阅读5页,还剩57页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Chapter6MoreConditionalsandLoops JavaSoftwareSolutionsFoundationsofProgramDesignSeventhEdition MoreConditionalsandLoops NowwecanfillinsomeadditionaldetailsregardingJavaconditionalandrepetitionstatementsChapter6focuseson theswitchstatementtheconditionaloperatorthedolooptheforloopdrawingwiththeaidofconditionalsandloopsdialogboxes Outline TheswitchStatementTheConditionalOperatorThedoStatementTheforStatementDrawingwithLoopsandConditionalsDialogBoxes TheswitchStatement TheswitchstatementprovidesanotherwaytodecidewhichstatementtoexecutenextTheswitchstatementevaluatesanexpression thenattemptstomatchtheresulttooneofseveralpossiblecasesEachcasecontainsavalueandalistofstatementsTheflowofcontroltransferstostatementassociatedwiththefirstcasevaluethatmatches TheswitchStatement Thegeneralsyntaxofaswitchstatementis switch expression casevalue1 statement list1casevalue2 statement list2casevalue3 statement list3case Ifexpressionmatchesvalue2 controljumpstohere TheswitchStatement Oftenabreakstatementisusedasthelaststatementineachcase sstatementlistAbreakstatementcausescontroltotransfertotheendoftheswitchstatementIfabreakstatementisnotused theflowofcontrolwillcontinueintothenextcaseSometimesthismaybeappropriate butoftenwewanttoexecuteonlythestatementsassociatedwithonecase TheswitchStatement switch option case A aCount break case B bCount break case C cCount break Anexampleofaswitchstatement TheswitchStatement AswitchstatementcanhaveanoptionaldefaultcaseThedefaultcasehasnoassociatedvalueandsimplyusesthereservedworddefaultIfthedefaultcaseispresent controlwilltransfertoitifnoothercasevaluematchesIfthereisnodefaultcase andnoothervaluematches controlfallsthroughtothestatementaftertheswitch TheswitchStatement Thetypeofaswitchexpressionmustbeintegers characters orenumeratedtypesAsofJava7 aswitchcanalsobeusedwithstringsYoucannotuseaswitchwithfloatingpointvaluesTheimplicitbooleanconditioninaswitchstatementisequalityYoucannotperformrelationalcheckswithaswitchstatementSeeGradeReport java GradeReport javaAuthor Lewis Loftus Demonstratestheuseofaswitchstatement importjava util Scanner publicclassGradeReport Readsagradefromtheuserandprintscommentsaccordingly publicstaticvoidmain String args intgrade category Scannerscan newScanner System in System out print Enteranumericgrade 0to100 grade scan nextInt category grade 10 System out print Thatgradeis continue continueswitch category case10 System out println aperfectscore Welldone break case9 System out println wellaboveaverage Excellent break case8 System out println aboveaverage Nicejob break case7 System out println average break case6 System out println belowaverage Youshouldseethe System out println instructortoclarifythematerial presentedinclass break default System out println notpassing continueswitch category case10 System out println aperfectscore Welldone break case9 System out println wellaboveaverage Excellent break case8 System out println aboveaverage Nicejob break case7 System out println average break case6 System out println belowaverage Youshouldseethe System out println instructortoclarifythematerial presentedinclass break default System out println notpassing SampleRunEnteranumericgrade 0to100 91Thatgradeiswellaboveaverage Excellent Outline TheswitchStatementTheConditionalOperatorThedoStatementTheforStatementDrawingwithLoopsandConditionalsDialogBoxes TheConditionalOperator TheconditionaloperatorevaluatestooneoftwoexpressionsbasedonabooleanconditionItssyntaxis condition expression1 expression2Iftheconditionistrue expression1isevaluated ifitisfalse expression2isevaluatedThevalueoftheentireconditionaloperatoristhevalueoftheselectedexpression TheConditionalOperator Theconditionaloperatorissimilartoanif elsestatement exceptthatitisanexpressionthatreturnsavalueForexample larger num1 num2 num1 num2 Ifnum1isgreaterthannum2 thennum1isassignedtolarger otherwise num2isassignedtolargerTheconditionaloperatoristernarybecauseitrequiresthreeoperands TheConditionalOperator Anotherexample Ifcountequals1 the Dime isprintedIfcountisanythingotherthan1 then Dimes isprinted System out println Yourchangeis count count 1 Dime Dimes QuickCheck Expressthefollowinglogicinasuccinctmannerusingtheconditionaloperator if val 10 System out println Itisnotgreaterthan10 elseSystem out println Itisgreaterthan10 QuickCheck Expressthefollowinglogicinasuccinctmannerusingtheconditionaloperator if val 10 System out println Itisnotgreaterthan10 elseSystem out println Itisgreaterthan10 System out println Itis val 10 not greaterthan10 Outline TheswitchStatementTheConditionalOperatorThedoStatementTheforStatementDrawingwithLoopsandConditionalsDialogBoxes ThedoStatement Adostatementhasthefollowingsyntax do statement list while condition Thestatement listisexecutedonceinitially andthentheconditionisevaluatedThestatementisexecutedrepeatedlyuntiltheconditionbecomesfalse LogicofadoLoop true false ThedoStatement Anexampleofadoloop ThebodyofadoloopexecutesatleastonceSeeReverseNumber java intcount 0 do count System out println count while count 5 ReverseNumber javaAuthor Lewis Loftus Demonstratestheuseofadoloop importjava util Scanner publicclassReverseNumber Reversesthedigitsofanintegermathematically publicstaticvoidmain String args intnumber lastDigit reverse 0 Scannerscan newScanner System in continue continueSystem out print Enterapositiveinteger number scan nextInt do lastDigit number 10 reverse reverse 10 lastDigit number number 10 while number 0 System out println Thatnumberreversedis reverse continueSystem out print Enterapositiveinteger number scan nextInt do lastDigit number 10 reverse reverse 10 lastDigit number number 10 while number 0 System out println Thatnumberreversedis reverse SampleRunEnterapositiveinteger 2896Thatnumberreversedis6982 Comparingwhileanddo Outline TheswitchStatementTheConditionalOperatorThedoStatementTheforStatementDrawingwithLoopsandConditionalsDialogBoxes TheforStatement Aforstatementhasthefollowingsyntax for initialization condition increment statement Logicofaforloop false TheforStatement Aforloopisfunctionallyequivalenttothefollowingwhileloopstructure initialization while condition statement increment TheforStatement Anexampleofaforloop for intcount 1 count 5 count System out println count TheinitializationsectioncanbeusedtodeclareavariableLikeawhileloop theconditionofaforloopistestedpriortoexecutingtheloopbodyTherefore thebodyofaforloopwillexecutezeroormoretimes TheforStatement Theincrementsectioncanperformanycalculation for intnum 100 num 0 num 5 System out println num AforloopiswellsuitedforexecutingstatementsaspecificnumberoftimesthatcanbecalculatedordeterminedinadvanceSeeMultiples javaSeeStars java Multiples javaAuthor Lewis Loftus Demonstratestheuseofaforloop importjava util Scanner publicclassMultiples Printsmultiplesofauser specifiednumberuptoauser specifiedlimit publicstaticvoidmain String args finalintPER LINE 5 intvalue limit mult count 0 Scannerscan newScanner System in System out print Enterapositivevalue value scan nextInt continue continueSystem out print Enteranupperlimit limit scan nextInt System out println System out println Themultiplesof value between value and limit inclusive are for mult value mult limit mult value System out print mult t Printaspecificnumberofvaluesperlineofoutputcount if count PER LINE 0 System out println continueSystem out print Enteranupperlimit limit scan nextInt System out println System out println Themultiplesof value between value and limit inclusive are for mult value mult limit mult value System out print mult t Printaspecificnumberofvaluesperlineofoutputcount if count PER LINE 0 System out println SampleRunEnterapositivevalue 7Enteranupperlimit 400Themultiplesof7between7and400 inclusive are 714212835424956637077849198105112119126133140147154161168175182189196203210217224231238245252259266273280287294301308315322329336343350357364371378385392399 Stars javaAuthor Lewis Loftus Demonstratestheuseofnestedforloops publicclassStars Printsatriangleshapeusingasterisk star characters publicstaticvoidmain String args finalintMAX ROWS 10 for introw 1 row MAX ROWS row for intstar 1 star row star System out print System out println Stars javaAuthor Lewis Loftus Demonstratestheuseofnestedforloops publicclassStars Printsatriangleshapeusingasterisk star characters publicstaticvoidmain String args finalintMAX ROWS 10 for introw 1 row MAX ROWS row for intstar 1 star row star System out print System out println Output QuickCheck Writeacodefragmentthatrollsadie100timesandcountsthenumberoftimesa3comesup QuickCheck Writeacodefragmentthatrollsadie100timesandcountsthenumberoftimesa3comesup Diedie newDie intcount 0 for intnum 1 num 100 num if die roll 3 count Sytem out println count TheforStatement EachexpressionintheheaderofaforloopisoptionalIftheinitializationisleftout noinitializationisperformedIftheconditionisleftout itisalwaysconsideredtobetrue andthereforecreatesaninfiniteloopIftheincrementisleftout noincrementoperationisperformed For eachLoops AvariantoftheforloopsimplifiestherepetitiveprocessingofitemsinaniteratorForexample supposebookListisanArrayListobjectThefollowingloopwillprinteachbook for BookmyBook bookList System out println myBook Thisversionofaforloopisoftencalledafor eachloop For eachLoops Afor eachloopcanbeusedonanyobjectthatimplementstheIterableinterfaceIteliminatestheneedtoretrieveaniteratorandcallthehasNextandnextmethodsexplicitlyItalsowillbehelpfulwhenprocessingarrays whicharediscussedinChapter8 QuickCheck Writeafor eachloopthatprintsalloftheStudentobjectsinanArrayListobjectcalledroster QuickCheck Writeafor eachloopthatprintsalloftheStudentobjectsinanArrayListobjectcalledroster for Studentstudent roster System out println student Outline TheswitchStatementTheConditionalOperatorThedoStatementTheforStatementDrawingwithLoopsandConditionalsDialogBoxes DrawingTechniques ConditionalsandloopsenhanceourabilitytogenerateinterestinggraphicsSeeBullseye javaSeeBullseyePanel javaSeeBoxes javaSeeBoxesPanel java Bullseye javaAuthor Lewis Loftus Demonstratestheuseofloopstodraw importjavax swing JFrame publicclassBullseye Createsthemainframeoftheprogram publicstaticvoidmain String args JFrameframe newJFrame Bullseye frame setDefaultCloseOperation JFrame EXIT ON CLOSE BullseyePanelpanel newBullseyePanel frame getContentPane add panel frame pack frame setVisible true Bullseye javaAuthor Lewis Loftus Demonstratestheuseofloopstodraw importjavax swing JFrame publicclassBullseye Createsthemainframeoftheprogram publicstaticvoidmain String args JFrameframe newJFrame Bullseye frame setDefaultCloseOperation JFrame EXIT ON CLOSE BullseyePanelpanel newBullseyePanel frame getContentPane add panel frame pack frame setVisible true BullseyePanel javaAuthor Lewis Loftus Demonstratestheuseofconditionalsandloopstoguidedrawing importjavax swing JPanel importjava awt publicclassBullseyePanelextendsJPanel privatefinalintMAX WIDTH 300 NUM RINGS 5 RING WIDTH 25 Setsupthebullseyepanel publicBullseyePanel setBackground Color cyan setPreferredSize newDimension 300 300 continue continue Paintsabullseyetarget publicvoidpaintComponent Graphicspage super paintComponent page intx 0 y 0 diameter MAX WIDTH page setColor Color white for intcount 0 count NUM RINGS count if page getColor Color black alternatecolorspage setColor Color white elsepage setColor Color black page fillOval x y diameter diameter diameter 2 RING WIDTH x RING WIDTH y RING WIDTH Drawtheredbullseyeinthecenterpage setColor Color red page fillOval x y diameter diameter Boxes javaAuthor Lewis Loftus Demonstratestheuseofloopstodraw importjavax swing JFrame publicclassBoxes Createsthemainframeoftheprogram publicstaticvoidmain String args JFrameframe newJFrame Boxes frame setDefaultCloseOperation JFrame EXIT ON CLOSE BoxesPanelpanel newBoxesPanel frame getContentPane add panel frame pack frame setVisible true Boxes javaAuthor Lewis Loftus Demonstratestheuseofloopstodraw importjavax swing JFrame publicclassBoxes Createsthemainframeoftheprogram publicstaticvoidmain String args JFrameframe newJFrame Boxes frame setDefaultCloseOperation JFrame EXIT ON CLOSE BoxesPanelpanel newBoxesPanel frame getContentPane add panel frame pack frame setVisible true BoxesPanel javaAuthor Lewis Loftus Demonstratestheuseofconditionalsandloopstoguidedrawing importjavax swing JPanel importjava awt importjava util Random publicclassBoxesPanelextendsJPanel privatefinalintNUM BOXES 50 THICKNESS 5 MAX SIDE 50 privatefinalintMAX X 350 MAX Y 250 privateRandomgenerator Setsupthedrawingpanel publicBoxesPanel generator newRandom setBackground Color black setPreferredSize newDimension 400 300 continue continue Paintsboxesofrandomwidthandheightinarandomlocation Narroworshortboxesarehighlightedwithafillcolor publicvoidpaintComponent Graphicspage super paintComponent page intx y width height for intcount 0 count NUM BOXES count x generator nextInt MAX X 1 y generator nextInt MAX Y 1 width generator nextInt MAX SIDE 1 height generator nextInt MAX SIDE 1 continue continueif width THICKNESS checkfornarrowbox page setColor Color yellow page fillRect x y width height elseif height THICKNESS checkforshortbox page setColor Color green page fillRect x y width height else page setColor Color white page drawRect x y width height
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 广东省惠州市2025年物理高一上期末质量检测试题含解析
- 黑龙江佳木斯市第一中学2025年高一物理第一学期期末综合测试试题含解析
- 河北省邯郸市永年区第二中学2026届高一化学第一学期期中质量跟踪监视试题含解析
- 现代物流工艺流程总结
- 止水条体积膨胀倍率试验记录
- 大学生职业生涯规划与就业创业指导(实践版)笔试题库 言语理解与表达1
- 高一数学上学期第三次月考(北师大版2019高效培优强化卷)(参考答案)
- 英语写作智能评阅系统对比研究-以iWrite和批改网为例
- 会计学术会议征文选题
- 学术访谈李少锋主编访谈录(附《应用语言学研究方法》第1期论文)
- T-CCIIA 0004-2024 精细化工产品分类
- 博途软件界面概述讲解
- TD/T 1060-2021 自然资源分等定级通则(正式版)
- 青少年犯罪心理学智慧树知到期末考试答案章节答案2024年鲁东大学
- 甲醇卸车过程风险安全技术培训
- MOOC 大学英语听说译-河南理工大学 中国大学慕课答案
- 知识点5.2 乳胶漆的原材料介绍
- 《红外热像法检测建筑外墙饰面层粘结缺陷分级与数据处理标准》
- 生涯发展报告 (修改)
- 三叉苦种植技术规程-征求意见稿
- 食品车间现场管理培训课件
评论
0/150
提交评论