版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
MoreConditionalsandLoopsNowwecanfillinsomeadditionaldetailsregardingJavaconditionalandrepetitionstatementsChapter6focuseson:theswitchstatementtheconditionaloperatorthedolooptheforloopdrawingwiththeaidofconditionalsandloopsdialogboxesOutlineTheswitch
StatementTheConditionalOperatorThedo
StatementThefor
StatementDrawingwithLoopsandConditionalsDialogBoxesTheswitchStatementTheswitchstatementprovidesanotherwaytodecidewhichstatementtoexecutenextTheswitchstatementevaluatesanexpression,thenattemptstomatchtheresulttooneofseveralpossiblecasesEachcasecontainsavalueandalistofstatementsTheflowofcontroltransferstostatementassociatedwiththefirstcasevaluethatmatchesTheswitchStatementThegeneralsyntaxofaswitchstatementis:switch(expression){casevalue1
:
statement-list1casevalue2
:
statement-list2casevalue3:
statement-list3
case
...}switchandcasearereservedwordsIfexpressionmatchesvalue2,controljumpstohereTheswitchStatementOftenabreakstatementisusedasthelaststatementineachcase'sstatementlistAbreakstatementcausescontroltotransfertotheendoftheswitchstatementIfabreakstatementisnotused,theflowofcontrolwillcontinueintothenextcaseSometimesthismaybeappropriate,butoftenwewanttoexecuteonlythestatementsassociatedwithonecaseTheswitchStatementswitch(option){case'A':aCount++;break;
case'B':bCount++;break;case'C':cCount++;break;}Anexampleofaswitchstatement:TheswitchStatementAswitchstatementcanhaveanoptionaldefaultcaseThedefaultcasehasnoassociatedvalueandsimplyusesthereservedworddefaultIfthedefaultcaseispresent,controlwilltransfertoitifnoothercasevaluematchesIfthereisnodefaultcase,andnoothervaluematches,controlfallsthroughtothestatementaftertheswitchTheswitchStatementThetypeofaswitchexpressionmustbeintegers,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");continuecontinue
switch(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.");}}}continue
switch(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.OutlineTheswitch
StatementTheConditionalOperatorThedo
StatementThefor
StatementDrawingwithLoopsandConditionalsDialogBoxesTheConditionalOperatorTheconditionaloperatorevaluatestooneoftwoexpressionsbasedonabooleanconditionItssyntaxis:condition?expression1:expression2Ifthecondition
istrue,expression1
isevaluated;ifitisfalse,expression2
isevaluatedThevalueoftheentireconditionaloperatoristhevalueoftheselectedexpressionTheConditionalOperatorTheconditionaloperatorissimilartoanif-elsestatement,exceptthatitisanexpressionthatreturnsavalueForexample: larger=((num1>num2)?num1:num2);Ifnum1isgreaterthannum2,thennum1isassignedtolarger;otherwise,num2isassignedtolargerTheconditionaloperatoristernarybecauseitrequiresthreeoperandsTheConditionalOperatorAnotherexample:Ifcount
equals1,the"Dime"isprintedIfcountisanythingotherthan1,then"Dimes"isprintedSystem.out.println("Yourchangeis"+count+((count==1)?"Dime":"Dimes"));QuickCheckExpressthefollowinglogicinasuccinctmannerusingtheconditionaloperator.if(val<=10)System.out.println("Itisnotgreaterthan10.");elseSystem.out.println("Itisgreaterthan10.");QuickCheckExpressthefollowinglogicinasuccinctmannerusingtheconditionaloperator.if(val<=10)System.out.println("Itisnotgreaterthan10.");elseSystem.out.println("Itisgreaterthan10.");System.out.println("Itis"+((val<=10)?"not":"")+"greaterthan10.");OutlineTheswitch
StatementTheConditionalOperatorThedo
StatementThefor
StatementDrawingwithLoopsandConditionalsDialogBoxesThedoStatementAdostatementhasthefollowingsyntax: do {
statement-list; } while(condition);
Thestatement-list
isexecutedonceinitially,andthenthecondition
isevaluatedThestatementisexecutedrepeatedlyuntiltheconditionbecomesfalseLogicofadoLooptrueconditionevaluatedstatementfalseThedoStatementAnexampleofadoloop:Thebodyofado
loopexecutesatleastonceSeeReverseNumber.javaintcount=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);continuecontinue
System.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);}}continue
System.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:2896Thatnumberreversedis6982ComparingwhileanddostatementtruefalseconditionevaluatedThewhileLooptrueconditionevaluatedstatementfalseThedoLoopOutlineTheswitch
StatementTheConditionalOperatorThedo
StatementThefor
StatementDrawingwithLoopsandConditionalsDialogBoxesTheforStatementAforstatementhasthefollowingsyntax:for(initialization;condition;increment)
statement;TheinitializationisexecutedoncebeforetheloopbeginsThestatement
isexecuteduntiltheconditionbecomesfalseTheincrement
portionisexecutedattheendofeachiterationLogicofaforloopstatementtrueconditionevaluatedfalseincrementinitializationTheforStatementAforloopisfunctionallyequivalenttothefollowingwhileloopstructure:initialization;while(condition){
statement;
increment;}TheforStatementAnexampleofaforloop: for(intcount=1;count<=5;count++) System.out.println(count);TheinitializationsectioncanbeusedtodeclareavariableLikeawhileloop,theconditionofaforloopistestedpriortoexecutingtheloopbodyTherefore,thebodyofaforloopwillexecutezeroormoretimesTheforStatementTheincrementsectioncanperformanycalculation: 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();continuecontinue
System.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();}}}continue
System.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:7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 112 119 126 133 140 147 154 161 168 175 182 189 196 203 210 217 224 231 238 245 252 259 266 273 280 287 294 301 308 315 322 329 336 343 350 357 364 371 378 385 392 399//********************************************************************//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*******************************************************QuickCheckWriteacodefragmentthatrollsadie100timesandcountsthenumberoftimesa3comesup.QuickCheckWriteacodefragmentthatrollsadie100timesandcountsthenumberoftimesa3comesup.Diedie=newDie();intcount=0;for(intnum=1;num<=100;num++)if(die.roll()==3)count++;Sytem.out.println(count);TheforStatementEachexpressionintheheaderofaforloopisoptionalIftheinitializationisleftout,noinitializationisperformedIftheconditionisleftout,itisalwaysconsideredtobetrue,andthereforecreatesaninfiniteloopIftheincrementisleftout,noincrementoperationisperformedFor-eachLoopsAvariantoftheforloopsimplifiestherepetitiveprocessingofitemsinaniteratorForexample,supposebookListisanArrayList<Book>
objectThefollowingloopwillprinteachbook: for(BookmyBook:bookList) System.out.println(myBook);Thisversionofaforloopisoftencalledafor-eachloopFor-eachLoopsAfor-eachloopcanbeusedonanyobjectthatimplementstheIterable
interfaceIteliminatestheneedtoretrieveaniteratorandcallthehasNextandnextmethodsexplicitlyItalsowillbehelpfulwhenprocessingarrays,whicharediscussedinChapter8QuickCheckWriteafor-eachloopthatprintsalloftheStudentobjectsinanArrayList<Student>objectcalledroster.QuickCheckWriteafor-eachloopthatprintsalloftheStudentobjectsinanArrayList<Student>objectcalledroster.for(Studentstudent:roster)System.out.println(student);OutlineTheswitch
StatementTheConditionalOperatorThedo
StatementThefor
StatementDrawingwithLoopsandConditionalsDialogBoxesDrawingTechniquesConditionalsandloopsenhanceourabilitytogenerateinterestinggraphicsSeeBullseye.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));
}continuecontinue////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));
}continuecontinue////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;continuecontinue
if(width<=THICKNESS)//checkfornarrowbox{page.setColor(Color.yellow);page.fillRect(x,y,width,height);}
else
if(height<=THICKNESS)//checkforshortbox{page.setColor(Color.green);page.fillRect(x,y,width,height);}
else
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2023年中国建设银行建银工程咨询有限责任公司招聘考试真题及答案
- 2023年新疆维吾尔自治区人民医院编制内引进考试真题及答案
- 2023年邯郸邱县招聘卫生专业技术人才考试真题及答案
- 注册监理工程师《合同管理》提分训练题
- 6 飞向蓝天的恐龙(教学设计)-2023-2024学年小学语文四年级下册统编版
- 2024非专利技术转让合同范本技术转让合同范本
- 教材采购合同样本
- 水管道维修合同范本
- 2024年早教中心主任聘用合同
- 2024年简单劳动合同模板
- 西方经济思想史(第三版)第08章马尔萨斯的经济思想
- 小学生心理健康主题班会PPT
- 蓝色科技风网络安全共享文明PPT模板
- 一年级上册数学教案-3.2 十几就是十和几 ▏沪教版
- 从陨石特征鉴别陨石
- 人教版一年级数学上册:第1-2单元检测卷(含答案)
- 【预习新知】六年级语文上册预习单
- 保温装饰一体板(陶瓷薄板)施工方案
- 正常心电图以及常见心律失常心电图表现
- 舒适化护理的研究现状与展望
- 《六月二十七日望湖楼醉书》_优质课件
评论
0/150
提交评论