Top Banner
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2017 Howard Rosenthal
32

Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

Oct 03, 2020

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

Selec%onandDecisionStructuresinJava:IfStatementsandSwitchStatements

CSC121Spring2017

HowardRosenthal

Page 2: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

LessonGoals� UnderstandsomeofJava’scontrolstructures� Understandhowtocontroltheflowofaprogramviaselectionmechanisms

� Understandif,if-else,else-ifandswitchstatements� Buildprogramswithnestedlayersofdecisionmaking

�  Buildingblocksofexecutioncode� Understandhowtodealwiththedanglingelse� Understandtheconditionaloperator

2

Page 3: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 4: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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.

Page 5: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

TheBasicSyntaxoftheifStatementif(booleanexpression){statement1;statement2;o0ostatementn;}�  Thestatementsinsidetheblock(delineatedbyapairofbraces)areexecutedonlyifthe

booleanstatement(inparentheses)istrue�  Youshouldusethebracesevenifthereisonlyasinglestatementinsidetheblockeven

thoughthisisn’trequired�  Nosemicolonontheifstatement�  Anifwithasinglestatementfollowingitdoesnotrequirecurlybraces,however,itus

besttousethemallthetimeatfirstif(booleanexpression)statement1;

5

Page 6: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

BasicTerminology� Anifstatementisalsocalledaconditionalorselectionstatement

� Thephraseif(booleanexpression)iscalledtheifclause�  Thebooleanexpressionitselfiscalledthecondition

� Thestatementsinsidethecurlybracescompriseablock

� Youcannestifstatementsinsideeachother

6

Page 7: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 8: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

TheBasicSyntaxoftheif-elseStatement�  Similartotheifstatement,butexclusivelyexecutesanalternativesetofstatement(s)iftheconditionalisfalseif(booleanexpression)//alwaysevaluatestoeithertrueorfalse{statement1;statement2;o0ostatementn;}else{statementa;statementb;o0ostatementx;}Note:Onceagainifthereisonlyasinglestatementthenbracesarenotrequiredif(booleanexpression)//alwaysevaluatestoeithertrueorfalsestatement1;else

statementa;

8

Page 9: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 10: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

ifelseifSyntax�  Allowsfortestingformultipledifferentconditions�  Onlythefirstcasethattestsastruewillbeexecuted�  Ifthereisnoelsestatementattheendthenitispossiblethatnoneoftheblocksareexecutedif(booleanexpression)//alwaysevaluatestoeithertrueorfalse{statement1;statement2;o0statementn;}elseif(booleanexpression)//alwaysevaluatestotrueorfalse{statementa;statementb;o0statementx;}else//optional{statementa;statementb;o0statementx;}

10

Page 11: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 12: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

ANoteOnbooleanExpressions� Becarefulwhenusingfloatordoubletypevariablesinbooleanexpressions�  Sincethereisalwayslimitedprecisionthepossibilityofanexecutionerrorexists,especiallyaftermorecomplexmathematicaloperations

�  Example:(7.13*2.9)/(3.6*2.95)maybedifferentthan(7.13/(3.6*2.95))*2.9SeeDecimalCompare.java

12

Page 13: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 14: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 15: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

DanglingifFlows

15

ifnum>0

ifnum<10

F

Print“aaa”

T

TPrint“bbb”

F

ifnum>0

ifnum<10

F

Print“aaa”

T

TPrint“bbb”

Page 16: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

TheDanglingif–TheRulesSummarized� Everyelsemustmatchwithauniqueif.Youcan'thavetwoormoreelsematchingtothesameif.Ifthereisnomatchingifforanelse,thenyourprogramwon'tcompile.

� Eachelsemustbeprecededbyavalidif�  Fortunately,yourprogramfailstocompileifyoudon'tdothis.

� UseBraces�  Ifyoualwaysuseablockforifbodyandelsebody,thenyoucanavoidconfusion.However,it'susefultoknowthecorrectrules.

16

Page 17: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 18: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 19: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 20: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 21: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

AFewAddi%onalNotesOntheswitchStatement� Everyswitchstatementcanbeimplementedasanif/ifelsetypestatement

�  Itdoesn’talwaysworktheotherwayaround� Obviouslyiftheif/elseisdoingmorecomplexcomparisons(i.e.>=)orusingfloatingpointnumbers,thenthiscan’tbeimplementedinaswitchstatement

21

Page 22: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 23: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

TheCondi%onalOperator(2)inta=7,b=21;System.out.println("Theminis:"+(a<b?a:b));Theoutputwouldbe:Theminis7

23

Page 24: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

TheCondi%onalOperator(3)doublevalue=-34.569;doubleabsValue;absValue=(value<0)?-value:value;-------------------Theconstantvalue+34.569isassignedtoabsValue

24

Page 25: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 26: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

NowThatYourProgramsAreGeWngMoreComplex…�  Alwayscheckyourprogramsthrougheachoftheelsecases,switchgatesetc.

�  Todothisyouneedtodevelopasetoftestcases�  Atestcasehascomponentsthatdescribeaninput,actionor

eventandanexpectedresponse,todetermineifafeatureofanapplicationisworkingcorrectly

�  Yourtestcasesmustbeexpansiveenoughtocoverthefullrangeofpossibilities�  Forinstanceifthereisastatementif(x>4)

youdon’tneedtotestforeverypossibilitygreaterthan4,butyouneedtotestforatleastonethatisgreaterthan4,onethatequals4andonethatislessthan4.

�  Typicallywebuildasoftwaretestverificationmatrix

26

Page 27: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 28: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 29: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 30: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 31: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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

Page 32: Selec%on and Decision Structures in Java: If Statements ...csc121csudhspring2017.weebly.com/uploads/2/2/7/6/...Lesson Goals Understand some of Java’s control structures Understand

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