Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2017 Howard Rosenthal
Selec%onandDecisionStructuresinJava:IfStatementsandSwitchStatements
CSC121Spring2017
HowardRosenthal
LessonGoals� UnderstandsomeofJava’scontrolstructures� Understandhowtocontroltheflowofaprogramviaselectionmechanisms
� Understandif,if-else,else-ifandswitchstatements� Buildprogramswithnestedlayersofdecisionmaking
� Buildingblocksofexecutioncode� Understandhowtodealwiththedanglingelse� Understandtheconditionaloperator
2
ControlStructuresinJava� TherearethreecontrolstructuresinJava
� SequenceStructure� BuiltintoJava� Ensuresthatstatementsexecuteoneaftertheotherintheorder
theyarewritten,unlessdirectedotherwise� SelectionStructure(Chapter4)
� Basedontruthorfalsity� InJavaincludestheif,if…else,if...elseif,andswitchstatements
� RepetitionStructure(Chapter5)� Allowsforrepetitionofthesamegroupofstatementsmultiple
times,aslongasaconditionismet� InJavaincludesthedo,do…while,for,andenhancedforstatements� Alsoknownasiterationstatementsorloopingstatements
3
WindshieldwipersarecontrolledwithanON-OFFswitch.Theflowchartatrightshowshowthisdecisionismade.Startatthetopofthechartthenfollowthelinetothequestion:isitraining?Theansweriseithertrueorfalse.Iftheansweristrue,
followthelinelabeledTrue,performtheinstructionsinthebox"wiperson",followthelineto"continue".
Iftheanswerisfalse,followthelinelabeledFalse,performtheinstructionsinthebox"wipersoff",followthelineto"continue".
TwoWayDecisions
4
Thewindshieldwiperdecisionisatwo-waydecision(sometimescalledabinarydecision).Thedecisionseemssmall,butinprogramming,complicateddecisionsaremadebyexecutingmanysmalldecisions.
TheBasicSyntaxoftheifStatementif(booleanexpression){statement1;statement2;o0ostatementn;}� Thestatementsinsidetheblock(delineatedbyapairofbraces)areexecutedonlyifthe
booleanstatement(inparentheses)istrue� Youshouldusethebracesevenifthereisonlyasinglestatementinsidetheblockeven
thoughthisisn’trequired� Nosemicolonontheifstatement� Anifwithasinglestatementfollowingitdoesnotrequirecurlybraces,however,itus
besttousethemallthetimeatfirstif(booleanexpression)statement1;
5
BasicTerminology� Anifstatementisalsocalledaconditionalorselectionstatement
� Thephraseif(booleanexpression)iscalledtheifclause� Thebooleanexpressionitselfiscalledthecondition
� Thestatementsinsidethecurlybracescompriseablock
� Youcannestifstatementsinsideeachother
6
AVerySimpleExamplepublic class SimpleIfStatementDemo1 { public static void main(String [] args) { //Declaring a variable "test" and initializing it with a value 10
int test = 10; //Checking if "test" is greater than 5 if (test > 5) { //This block will be executed only if "test" is greater than 5 System.out.println("Success"); } //The if block ends. System.out.println("Executed successfully"); } }
7
TheBasicSyntaxoftheif-elseStatement� Similartotheifstatement,butexclusivelyexecutesanalternativesetofstatement(s)iftheconditionalisfalseif(booleanexpression)//alwaysevaluatestoeithertrueorfalse{statement1;statement2;o0ostatementn;}else{statementa;statementb;o0ostatementx;}Note:Onceagainifthereisonlyasinglestatementthenbracesarenotrequiredif(booleanexpression)//alwaysevaluatestoeithertrueorfalsestatement1;else
statementa;
8
ASimpleExampleofif-elseimportjava.util.Scanner;classNumberTester{publicstaticvoidmain(String[]args){Scannerkeyboard=newScanner(System.in);intnum;System.out.println("Enteraninteger:");num=keyboard.nextInt();if(num<0){System.out.println("Thenumber"+num+"isnegative");num=num+5;}else{System.out.println("Thenumber"+num+"iszeroorpositive");
num=num-4;}
System.out.println("Thenumberisnow"+num);System.out.println("Good-byefornow");
}}
9
ifelseifSyntax� Allowsfortestingformultipledifferentconditions� Onlythefirstcasethattestsastruewillbeexecuted� Ifthereisnoelsestatementattheendthenitispossiblethatnoneoftheblocksareexecutedif(booleanexpression)//alwaysevaluatestoeithertrueorfalse{statement1;statement2;o0statementn;}elseif(booleanexpression)//alwaysevaluatestotrueorfalse{statementa;statementb;o0statementx;}else//optional{statementa;statementb;o0statementx;}
10
AnelseifExample//Thisprogramassignsalettergradebasedonacharactergradeimportjava.util.Scanner;classIfElseDemo{publicstaticvoidmain(String[]args){
Scannerkeyboard=newScanner(System.in);System.out.println("Enterthegrade");inttestScore=keyboard.nextInt();
chargrade;if(testScore>=90){
grade='A';}elseif(testScore>=80){grade='B';}elseif(testScore>=70){grade='C';}elseif(testScore>=60){grade='D';}else{grade='F';}System.out.println("Grade="+grade);}} 11
Note:• Ifyoureversetheorderthenyouwouldneed
tocomparefrombottomtotopusing<=• Becarefulinuseof>vs.>=,etc.• Remember,foranyparticularlevelofif,else-if,
else,onlytheblockafterthefirsttruestatementisexecuted
ANoteOnbooleanExpressions� Becarefulwhenusingfloatordoubletypevariablesinbooleanexpressions� Sincethereisalwayslimitedprecisionthepossibilityofanexecutionerrorexists,especiallyaftermorecomplexmathematicaloperations
� Example:(7.13*2.9)/(3.6*2.95)maybedifferentthan(7.13/(3.6*2.95))*2.9SeeDecimalCompare.java
12
TheDanglingif(1)� Rule-Anelsematcheswiththenearest,previous,unmatchedifthat'snotinablock.if(num>0){if(num<10)//PreviousunmatchedifSystem.out.println("aaa");else//MatcheswithpreviousunmatchedifSystem.out.println("bbb");}Intheexampleabove,theelseisindentedwiththeinnerifstatement.Itprints"bbb"onlyifnum>0andnum>=10,whichmeansitprintsonlyifnumis10orgreater.Intheexamplebelow,theelseisindentedwiththeouterifstatement.if(num>0){if(num<10)//PreviousunmatchedifSystem.out.println("aaa");else//MatcheswithpreviousunmatchedifSystem.out.println("bbb");}
Whichonedoeselsematchwith?Itpickstheclosestifunlessthereisafurtherclarificationwiththeuseofbraces.Thisphenomenonofhavingtopickbetweenoneoftwopossibleifstatementsiscalledthedanglingelse.
� Dependingonwhichiftheelseispairedwith,youcangetdifferentresults.Bynow,youshouldknowthatJavadoesn'tpayattentiontoindentation.SobothexamplesabovearethesametoJava,whichmeansthatitmakesitsdeterminationbasedstrictlyonthesyntax.TotheJavaCompilerthereisnoambiguity(Youcan’tsay“That’snotwhatIreallymeant”)
� Thecompilerdoesn’tcareaboutindenting.Butyoushouldforclarity
13
TheDanglingif(2)� Whatifwewantedtheelsetomatchwiththefirstif?Then,weneedbraces.if(num>0)//Previousunmatchedif{if(num<10)//Unmatched,butinblockSystem.out.println("aaa");}else//MatcheswithpreviousunmatchedifnotinblockSystem.out.println("bbb");//Thisprintsifnum<=0.Theelseabovematcheswiththeprevious,unmatchedifnotinthelowerlevelblock.Thishappenstobetheouterif.Thereisanunmatchedifthat'stheinnerif,butthat'sinablock,soyoucan'tmatchtoit.Noticetheelsesitsoutsideoftheblock.Anelsedoesnotmatchtoapreviousififtheelseisoutsidetheblock,wheretheclosestifisfound.
14
DanglingifFlows
15
ifnum>0
ifnum<10
F
Print“aaa”
T
TPrint“bbb”
F
ifnum>0
ifnum<10
F
Print“aaa”
T
TPrint“bbb”
TheDanglingif–TheRulesSummarized� Everyelsemustmatchwithauniqueif.Youcan'thavetwoormoreelsematchingtothesameif.Ifthereisnomatchingifforanelse,thenyourprogramwon'tcompile.
� Eachelsemustbeprecededbyavalidif� Fortunately,yourprogramfailstocompileifyoudon'tdothis.
� UseBraces� Ifyoualwaysuseablockforifbodyandelsebody,thenyoucanavoidconfusion.However,it'susefultoknowthecorrectrules.
16
TheswitchStatement� Thesyntaxofaswitchstatementlookslike:switch(expr){caseliteral1:caseliteral1bodycaseliteral2:caseliteral2bodycaseliteral3:caseliteral3bodydefault:defaultbody}� Unlikeifstatementswhichcontainaconditionintheparentheses,switchcontainsanexpression.Thisexpression
mustbetypebyte,short,int,charorString.(Note:Stringisanewerfeature,andthebooksaysonlyintorchar).Wrapperclassescanalsobeusedbutthesewon’tbediscussedthissemester
� Thesemanticsofswitchare:� Evaluatetheexpression� Beginlookingateachcase,startingtoptobottom� Ifthevalueoftheexpressionmatchesthecase,thenrunthebody� Note:Thecasekeywordhastobefollowedbyaliteraloraconstantexpression.Itcan'tbearange� Ifyourunabreakstatement,youthenexittheswitch� Ifyoudon'trunabreakstatement,andyouareattheendofabody,runthenextbody.Keeprunningbodies
untilyouexitorhitabreakstatement� Ifnomatchismadetothecases,runthedefault,ifitexists.Thedefaultcaseisalwaysrunlast,nomatterwhere
itappears.(Itshouldbeplacedlast,though).Itisnotmandatorytohaveadefaultstatement.
17
ExamplesoftheSwitchStatementintx=4;switch(x){case2:System.out.println("TWO");break;case4:System.out.println("FOUR");break;case6:System.out.println("SIX");break;default:System.out.println("DEFAULT");}� Thisevaluatesxto4.Itskipscase2sincethevalue4doesn'tmatch2.Itdoesmatch
case4.Itrunsthebodyandprints“FOUR".Thenitrunsbreakandexitstheswitch.
18
ExamplesoftheSwitchStatement(2)� Mostofthetimes,youwillendeachcasewithbreak.BothCandlanguageslikeJavaforceyoutowriteastatement
thatshouldbethereallthetime.Let'sseewhathappenswhenyouleaveitout.intx=4;switch(x){case2:System.out.println("TWO");case4:System.out.println("FOUR");case6:System.out.println("SIX");default:System.out.println("DEFAULT");}� Thisprintsout:FOURSIXDEFAULT� That'sprobablynotwhattheuserhadinmind.Withoutthebreak,eachtimeabodyruns,itfallsthroughandstarts
runningthenextbody,andthenext,afteritmatchesthecorrectcase.� However,therearecaseswhereyouwillwanttoexecutemultiplestatementsfrommultiplecases(seenextexample)
19
ExamplesoftheSwitchStatement(3)� Youcancombinecasestogether.intx=4;switch(x){case1:case3:case5:System.out.println("ODD");break;case2:case4:case6:System.out.println("EVEN");break;default:System.out.println("DEFAULT");}
20
AFewAddi%onalNotesOntheswitchStatement� Everyswitchstatementcanbeimplementedasanif/ifelsetypestatement
� Itdoesn’talwaysworktheotherwayaround� Obviouslyiftheif/elseisdoingmorecomplexcomparisons(i.e.>=)orusingfloatingpointnumbers,thenthiscan’tbeimplementedinaswitchstatement
21
TheCondi%onalOperator(1)� Theconditionaloperatorisusedlikethis:true-or-false-condition?value-if-true:value-if-false� Hereishowitworks:
� Thetrue-or-false-conditionevaluatestotrueorfalse.� Thatvalueselectsonechoice:
� Ifthetrue-or-false-conditionistrue,thenevaluatetheexpressionbetween?and:
� Ifthetrue-or-false-conditionisfalse,thenevaluatetheexpressionbetween:andtheend.
� Theresultofevaluationisthevalueoftheentireconditionalexpression.
� Thisapproachcanbeusedinassignmentstatements
22
TheCondi%onalOperator(2)inta=7,b=21;System.out.println("Theminis:"+(a<b?a:b));Theoutputwouldbe:Theminis7
23
TheCondi%onalOperator(3)doublevalue=-34.569;doubleabsValue;absValue=(value<0)?-value:value;-------------------Theconstantvalue+34.569isassignedtoabsValue
24
importjava.util.Scanner;classRainTester{publicstaticvoidmain(String[]args){Scannerkeyboard=newScanner(System.in);Stringanswer;System.out.print("Isitraining?(YorN):");answer=keyboard.nextLine();if(answer.equals("Y"))//isanswerexactly"Y"?System.out.println("WipersOn");//truebranchelseSystem.out.println("WipersOff");//falsebranch}}
AnExampleUsingStringFeaturesThatWillBeTaughtLater
25
NowThatYourProgramsAreGeWngMoreComplex…� Alwayscheckyourprogramsthrougheachoftheelsecases,switchgatesetc.
� Todothisyouneedtodevelopasetoftestcases� Atestcasehascomponentsthatdescribeaninput,actionor
eventandanexpectedresponse,todetermineifafeatureofanapplicationisworkingcorrectly
� Yourtestcasesmustbeexpansiveenoughtocoverthefullrangeofpossibilities� Forinstanceifthereisastatementif(x>4)
youdon’tneedtotestforeverypossibilitygreaterthan4,butyouneedtotestforatleastonethatisgreaterthan4,onethatequals4andonethatislessthan4.
� Typicallywebuildasoftwaretestverificationmatrix
26
SampleTestMatrix
Y 2 3 4 X 1 R1 R2 R3 2 R4 R5 R6 5 R7 R8 R9 7 R10 R11 R12
27
• Testforallpossiblecombinations• Whentherearemultiplevariablesbreakthetestingintosmallerpieces• Alwaystestfordifferentandoutlyingconditions
• Positive,zeroandnegativenumbers• Firstandlastnumberandsomeelementinthemiddlewhen
processingalist
SpecialTopic-Rounding� Javaincludesdifferentmethodsandtechniquesforrounding,someofwhichwewill
learnlaterthisyear� However,ifyouareinterestedinroundingdothefollowing:1. Takethefloatingpointnumberandmultiplyby1000;Castthenumbermultipliedby
1000asanint(ifitisnottoolargeforanint,otherwiseuselong2. Taketheoriginalfloatingpointnumberandmultiplyby100;Castthenumber
multipliedby100asanint(ifitisnottoolargeforanint,otherwiseuselong3. Determineifthelastdigitoftheintvaluemultipliedby1000isgreaterthanorequal
to54. Ifthelastdigitisgreaterthanorequalto5divideby100.0andadd1,otherwisedivide
by100Example:doublex=123.45678,xRound;intxIntThous=(int)(x*1000);//thisis123456intxIntHund=(int)(x*100);//thisis12345if(xIntThous%10>=5)xRound=(xIntHund+1)/100.;elsexRound=(xIntHund/100.);SeefullprograminRoundingExample.java
28
ProgrammingExercises–Class(1)Exercise 1. Sort Three Write a program that requests the entry of three integers and displays the numbers in order from lowest to highest. Note: You will need to test all possible cases
29
ProgrammingExercises–Class(2)Exercise 8. Toll Free Numbers As of the year 2008, a 10 digit number that begins with 800, 888, 877, or 866 has been toll free. Write a program that reads in a 10 digit phone number and displays a message that states whether the number is toll free or not.
30
ProgrammingExercises–Lab(1)Exercise 3. Positive Sum Write a program that prompts for five integers and calculates the sum of those that are positive.
31
ProgrammingExercises–Lab(2)Exercise11. Grade Conversion A certain school assigns number grades ranging from 0-100. Write a program that queries the user for a numerical score and converts the score to a letter grade according to thee following criteria: 0-59:F; 60-69 D: 70-72, C-: 73-76, C: 77-79 C+; 80-82: B-; 83-86: B; 87-89: B+; 90-92: A-; 93-96: A; 97-100 A+
32