版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
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. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年無償使用政府辦公樓場地舉辦會議合同范本3篇
- 陜西交通職業(yè)技術學院《中國現(xiàn)當代文學Ⅱ》2023-2024學年第一學期期末試卷
- 探索紅色經(jīng)典:《紅巖》教學2篇
- 2024美容院股權轉讓與生態(tài)圈構建合作協(xié)議3篇
- 二零二五年度餐飲企業(yè)品牌戰(zhàn)略規(guī)劃合同6篇
- 2025年度廠房租賃合同解除及退還押金合同范本4篇
- 2025年度臨時租用文化用地租賃及文化活動合作協(xié)議4篇
- 二零二五年度旅游教育培訓機構合作協(xié)議范本4篇
- 2025年洗車租賃合同范本(含節(jié)假日優(yōu)惠活動)2篇
- 二零二五年服裝加工及品牌授權合同3篇
- 非誠不找小品臺詞
- 2024年3月江蘇省考公務員面試題(B類)及參考答案
- 患者信息保密法律法規(guī)解讀
- 老年人護理風險防控PPT
- 充電樁采購安裝投標方案(技術方案)
- 醫(yī)院科室考勤表
- 鍍膜員工述職報告
- 春節(jié)期間化工企業(yè)安全生產(chǎn)注意安全生產(chǎn)
- 保險行業(yè)加強清廉文化建設
- Hive數(shù)據(jù)倉庫技術與應用
- 數(shù)字的秘密生活:最有趣的50個數(shù)學故事
評論
0/150
提交評論