Presentation is loading. Please wait.

Presentation is loading. Please wait.

Nested Structures Chapters 3 & 4. Outline n Conditionals inside loops n Conditionals inside conditionals n If-else-if controls n Loops inside loops n.

Similar presentations


Presentation on theme: "Nested Structures Chapters 3 & 4. Outline n Conditionals inside loops n Conditionals inside conditionals n If-else-if controls n Loops inside loops n."— Presentation transcript:

1 Nested Structures Chapters 3 & 4

2 Outline n Conditionals inside loops n Conditionals inside conditionals n If-else-if controls n Loops inside loops n The switch control n The do-while loop

3 Program Flow n Beginning: Sequential flow first command, second, third, …, lastfirst command, second, third, …, last n Next: Conditional execution one-way: if (…) { … }one-way: if (…) { … } two-way: if (…) { … } else { … }two-way: if (…) { … } else { … } n Loops: indefinite: while (…) { … }indefinite: while (…) { … } definite: for (…; …; …) { … }definite: for (…; …; …) { … }

4 Inside the Conditional / Loop n Sequential flow first command, second, third, …, lastfirst command, second, third, …, last n But can put anything inside the {} if, if-else, while, for, … (other things, too!)if, if-else, while, for, … (other things, too!) n And then you can put anything inside those as deep as you want to goas deep as you want to go (but usually not more than three levels)(but usually not more than three levels)

5 Loops with Conditionals n For each positive integer the user enters, say whether it’s divisible by 5 stop when enter a negative numberstop when enter a negative number System.out.println(“Enter some numbers below: ”); num = kbd.nextInt(); while (num >= 0) { // TODO: say whether num is divisible by 5 // TODO: say whether num is divisible by 5 // get next number // get next number num = kbd.nextInt(); num = kbd.nextInt();}kbd.nextLine();

6 Expected Output n Pattern: Print, Read, repeat ((Divisible OR NotDivisible), Read)Print, Read, repeat ((Divisible OR NotDivisible), Read) Enter some numbers below: 49 49 is NOT divisible by 5. 95 95 is divisible by 5. 72 72 is NOT divisible by 5. Print Read NotDivisible Read Divisible Read NotDivisible Read Or: Print, repeat (Read, (Divisible OR NotDivisible)), Read But then we wouldn’t know when to stop looping!

7 Loops with Conditionals n whether divisible  if-else control while (num >= 0) { // say whether num is divisible by 5 // say whether num is divisible by 5 if (num % 5 == 0) { if (num % 5 == 0) { System.out.println(num + “ is divisible by 5.”); System.out.println(num + “ is divisible by 5.”); } else { } else { System.out.println(num + “ is not divisible by 5.”); System.out.println(num + “ is not divisible by 5.”); } // get next number // get next number num = kbd.nextInt(); num = kbd.nextInt();}

8 Note the Indentation n Each level  4 more spaces while (num >= 0) { // say whether num is divisible by 5 // say whether num is divisible by 5 if (num % 5 == 0) { if (num % 5 == 0) { System.out.println(num + “ is divisible by 5.”); System.out.println(num + “ is divisible by 5.”); } else { } else { System.out.println(num + “ is not divisible by 5.”); System.out.println(num + “ is not divisible by 5.”); } // get next number // get next number num = kbd.nextInt(); num = kbd.nextInt();} 81216 Remember the Format command!

9 Loop + Conditional Execution n whether divisible  if-else control while (num >= 0) { // say whether num is divisible by 5 // say whether num is divisible by 5 if (num % 5 == 0) { if (num % 5 == 0) { System.out.println(num + “ is divisible by 5.”); System.out.println(num + “ is divisible by 5.”); } else { } else { System.out.println(num + “ is not divisible by 5.”); System.out.println(num + “ is not divisible by 5.”); } // get next number // get next number num = kbd.nextInt(); num = kbd.nextInt();} 100 is divisible by 5 80 is divisible by 5 95 is divisible by 5 78 is NOT divisible by 5 84 is NOT divisible by 5 90 is divisible by 5

10 Exercise n Write a loop to read in six grades print “Good work!” if that grade is 90+print “Good work!” if that grade is 90+ n Use a for loop (why?) Enter your grade on A1: 100 Good work! Enter your grade on A2: 80 Enter your grade on A3: 95 Good work! Enter your grade on A4: 78 Enter your grade on A5: 84 Enter your grade on A6: 90 Good work!

11 if-else inside if-else What time is it? 9 pm Good evening! What time is it? 9 am Good morning! What time is it? 3 pm Good afternoon! What time is it? 3 am Good grief! Evening: 6pm to 11pm. Afternoon: 12pm to 5pm. Morning: 7am to 11am. 12am to 6 am. pmam A E M G

12 Get the Time // create variables Scanner kbd = new Scanner(System.in); int hour; String amPM; // get the time System.out.println(“What time is it?”); hour = kbd.nextInt(); // fix weird clock if (hour == 12) { hour = 0; } // NOTE: read next word in lower case amPM = kbd.next().toLowerCase(); kbd.nextLine();// read the Enter key!

13 Print the Message // print the appropriate message if ( amPM.equals(“pm”) ) { if ( hour < 6 ) { if ( hour < 6 ) { System.out.println(“Good afternoon!”); System.out.println(“Good afternoon!”); } else { } else { System.out.println(“Good evening!”); System.out.println(“Good evening!”); } } else { if ( hour > 6 ) { if ( hour > 6 ) { System.out.println(“Good morning!”); System.out.println(“Good morning!”); } else { } else { System.out.println(“Good grief!”); System.out.println(“Good grief!”); }} A E M G

14 9 AM Message // print the appropriate message if ( amPM.equals(“pm”) ) { if ( hour < 6 ) { if ( hour < 6 ) { System.out.println(“Good afternoon!”); System.out.println(“Good afternoon!”); } else { } else { System.out.println(“Good evening!”); System.out.println(“Good evening!”); } } else { if ( hour > 6 ) { if ( hour > 6 ) { System.out.println(“Good morning!”); System.out.println(“Good morning!”); } else { } else { System.out.println(“Good grief!”); System.out.println(“Good grief!”); }} “am”.equals(“pm”)? NO 9 > 6? YES

15 Note Indentation // print the appropriate message if ( amPM.equals(“pm”) ) { if ( hour < 6 ) { if ( hour < 6 ) { System.out.println(“Good afternoon!”); System.out.println(“Good afternoon!”); } else { } else { System.out.println(“Good evening!”); System.out.println(“Good evening!”); } } else { if ( hour > 6 ) { if ( hour > 6 ) { System.out.println(“Good morning!”); System.out.println(“Good morning!”); } else { } else { System.out.println(“Good grief!”); System.out.println(“Good grief!”); }} 81216 Remember the Format command!

16 if inside if n You can put if controls inside if controls if first condition is true, test second conditionif first condition is true, test second conditionSystem.out.println(“A”); if (condition1) { System.out.println(“B”); System.out.println(“B”); if (condition2) { if (condition2) { System.out.println(“C”); System.out.println(“C”); }} possible output: A AB ABC pattern: always A sometimes B when B, sometimes C

17 Eligible for Pension n Who is eligible for a pension seniors (age is 65+)seniors (age is 65+) disabled people 55+ who live on their owndisabled people 55+ who live on their own n Only ask question if need to know ask ageask age if 55..64, ask if disabledif 55..64, ask if disabled »if disabled, ask if live on own

18 Eligible for Pension // ask age System.out.print(“How old are you? ”); age = kbd.nextInt(); kbd.nextLine(); eligible = (age >= 65); // if 55..64, ask if disabled if (age >= 55 && !eligible) { System.out.print(“Are you disabled? ”); System.out.print(“Are you disabled? ”); answer = kbd.nextLine().toLowerCase(); answer = kbd.nextLine().toLowerCase(); // if disabled, ask if live on own // if disabled, ask if live on own if (answer.startsWith(“y”)) { if (answer.startsWith(“y”)) { System.out.print(“Do you live on your own? ”); System.out.print(“Do you live on your own? ”); answer = kbd.nextLine().toLowerCase(); answer = kbd.nextLine().toLowerCase(); } eligible = answer.startsWith(“y”); eligible = answer.startsWith(“y”);}

19 Exercise n Write nested if/if-else to generate: either “A”, “AB”, “ABC” or “ABD”either “A”, “AB”, “ABC” or “ABD” either “A”, “ABC” or “AC”either “A”, “ABC” or “AC” either “A”, “ABC”, or “D”either “A”, “ABC”, or “D”

20 Three-Way Choice n Exactly one of three options either “A”, “B”, or “C”either “A”, “B”, or “C” if (age < 18) { System.out.print(“Child”);} if (age >= 18 && age = 18 && age < 65) {System.out.print(“Adult”);} if (age >= 65) { System.out.print(“Senior”);} Child age is 15 Adult age is 25 Senior age is 65

21 Sequential If and If-Else n Be careful mixing if with if-else else parts go with each if separatelyelse parts go with each if separately if (age < 18) { System.out.print(“Child”);} if (age >= 18 && age = 18 && age < 65) {System.out.print(“Adult”); } else { System.out.print(“Senior”);} What happens when age = 15? Adult age is 25 Senior age is 65

22 If-Else Inside Else n If-Else inside an Else only do Adult/Senior choice if Child not chosenonly do Adult/Senior choice if Child not chosen if (age < 18) { System.out.print(“Child”); } else { if (age >= 18 && age = 18 && age < 65) { System.out.print(“Adult”); System.out.print(“Adult”); } else { } else { System.out.print(“Senior”); System.out.print(“Senior”); }} Adult age is 25 Senior age is 65 What happens when age = 15?

23 If-Else Inside Else n If-Else inside an Else usually written this way (3-way choice)usually written this way (3-way choice) if (age < 18) { System.out.print(“Child”); } else if (age >= 18 && age = 18 && age < 65) {System.out.print(“Adult”); } else { System.out.print(“Senior”);} Adult age is 25 Senior age is 65 What happens when age = 15?

24 Cascading If Statements n Simplified conditions already know age >= 18 in part 2already know age >= 18 in part 2 if (age < 18) { System.out.print(“Child”); } else if (age < 65) { System.out.print(“Adult”); } else { System.out.print(“Senior”);} Adult age is 25 Senior age is 65 What happens when age = 15?

25 Multi-Way Choice A or B or C or... or Z if (...) { doA(); } else if (...) { doB();... } else { doZ();} A or B or... or Z or none of the above if (...) { doA(); } else if (...) { doB();... doZ();} If we didn’t do any of the others, then we’ll do Z for sure If we didn’t do any of the others, we still might not do Z

26 Exercises n Write “Good morning” if time < 12, “Good afternoon” if 12  time < 17, “Good evening” otherwise n Write “Small” if size is 1, “Medium” if size is 2, “Large” if size is 3, “X-Large” if size is 4, and “XX-Large” if size is 5 don’t write anything if size is not 1..5don’t write anything if size is not 1..5

27 Using Braces n Always use braces on if controls if (…) { … }if (…) { … } if (…) { … } else { … }if (…) { … } else { … } n Indent the body of the conditional if (…) { // this part is called the “head” … // this part is called the “body” }if (…) { // this part is called the “head” … // this part is called the “body” }

28 Optional Braces n Sometimes braces can be left off n Braces can be left of if (and only if) there is exactly one conditional command if (thisIsTrue) doThat(); if (thisIsTrue) doThat(); n Use the braces then anyway it’ll save you from making some mistakes!it’ll save you from making some mistakes!

29 Mistake #1 n Thinking it’s the indentation that matters this code generates an error message:this code generates an error message: if (thisIsTrue) doThis(); andThat(); else thisOther();if (thisIsTrue) doThis(); andThat(); else thisOther(); “else without if”“else without if”

30 Mistake #1a n Putting braces around everything after if this code generates the same error message:this code generates the same error message: if (thisIsTrue) { doThis(); andThat(); else thisOther(); }if (thisIsTrue) { doThis(); andThat(); else thisOther(); } “else without if”“else without if”

31 Mistake #2 n Connecting else to wrong if if (n1 > 0) if (n2 > 0) if (n2 > 0) System.out.println(“Both positive”); System.out.println(“Both positive”);else System.out.println(“Ummm?”); System.out.println(“Ummm?”); when does “Ummm?” get printed?when does “Ummm?” get printed? »n1 <= 0? NO »n2 <= 0? YES

32 Use Braces! if (n1 > 0) { if (n2 > 0) { if (n2 > 0) { System.out.println(“Both positive”); System.out.println(“Both positive”); System.out.println(“For sure”); System.out.println(“For sure”); } } else { System.out.println(“n1 is negative”); System.out.println(“n1 is negative”);}

33 Exercise n What are the possible outputs of this code? System.out.print(“A”); if (…) { System.out.print(“B”); System.out.print(“B”); if (…) if (…) System.out.print(“C”); System.out.print(“C”); System.out.print(“D”); System.out.print(“D”); } else System.out.print(“E”); System.out.println(“F”); Are you sure? Maybe you should “format” the code and look again!

34 Loops inside Loops n Draw four lines with 20 stars on each line four lines all the same  a “for” loopfour lines all the same  a “for” loop each line:each line: »twenty stars, all the same  another “for” loop »line ends after the twenty stars ********************

35 Drawing One Line n Need a line of 20 (or whatever) stars 20 times (print out one star)20 times (print out one star) then end the linethen end the line // for each of the 20 stars for (int star = 1; star <= 20; ++star) { // print that star // print that star System.out.print(“*”); System.out.print(“*”);} // end that line (after all the stars) System.out.println(); ********************

36 Drawing Multiple Lines n Need 4 lines 4 times (print out one line)4 times (print out one line) // for each of the four lines for (int line = 1; line <= 4; ++line) { // print one line // print one line …// same code as before …// same code as before …// including the loop! …// including the loop!} ********************

37 Loops inside Loops n Draw four lines with 20 stars on each line // for each of the four lines for (int line = 1; line <= 4; ++line) { // for each of the 20 stars // for each of the 20 stars for (int star = 1; star <= 20; ++star) { for (int star = 1; star <= 20; ++star) { // print that star // print that star System.out.print(“*”); System.out.print(“*”); } // end that line (after all the stars) // end that line (after all the stars) System.out.println(); System.out.println();}

38 Inner and Outer Loops n One loop (inner) inside another (outer) // print a rectangle for (int line = 1; line <= height; line++) { // print a line of stars // print a line of stars for (int star = 1; star <= width; star++) { // print a star System.out.print(‘*’);}System.out.println();} inner loop outer loop Notice that it doesn’t matter what you name the loop control variable, so long as you stick with the one name for each loop.

39 Identify the Pieces and Patterns n Write nested loops to read numbers (integers) until a negative number is read print that many “Hello”s on one lineprint that many “Hello”s on one line How many hellos? 5 Hello! Hello! Hello! Hello! Hello! How many hellos? 3 Hello! Hello! Hello! How many hellos? 7 Hello! Hello! Hello! Hello! Hello! Hello! Hello! How many hellos? -1

40 Inner and Outer Loops Outer loop n Read numbers until a negative number is read n while loop: Inner loop n Print out a given number of “Hello”s told number before starttold number before start n for loop: S.o.p.(“How many Hellos? ”); num = kbd.nextInt(); kbd.nextLine(); while (num >= 0) { // inner loop goes HERE S.o.p.(“How many Hellos? ”); num = kbd.nextInt(); kbd.nextLine(); } for (int i = 1; i <= num; ++i) { S.o.p.(“Hello! ”); } System.out.println(); Change S.o.p. to System.out.print

41 Identify the Pieces and Patterns n Write nested loops to read three valid assignment scores and calculate their average valid = between 0 and 100 (inclusive)valid = between 0 and 100 (inclusive) Enter your A1 score: 67 Enter your A2 score: 789 That’s not valid. Try again! Enter your A2 score: 79 Enter your A3 score: 1000 That’s not valid. Try again! Enter your A3 score: 100 Your average: 82.0%

42 Declaring Variables in Loops n You can actually declare variables inside loop (and conditional) bodies for (a = 1; a <= NUM_ASGN; a++) { System.out.println(“Enter grade:”); System.out.println(“Enter grade:”); int grade = kbd.nextInt(); int grade = kbd.nextInt(); kbd.nextLine(); kbd.nextLine(); sum += grade; sum += grade;} that variable belongs to the loop!that variable belongs to the loop! cannot be used outside the loopcannot be used outside the loop

43 “Scope” of a Variable n Cannot use variable outside its scope for (a = 1; a <= NUM_ASGN; a++) { System.out.println(“Enter grade: ”); System.out.println(“Enter grade: ”); int grade = kbd.nextInt(); int grade = kbd.nextInt(); kbd.nextLine(); kbd.nextLine(); sum += grade; sum += grade;} S.o.pln(“Last grade was ” + grade); OutOfScope.java:30: Cannot find symbol symbol : variable grade The “scope” of grade

44 Declaring Loop Control Variable n Often declare LCV of for loop in the loop for (int aa = 1; aa <= NUM_ASGN; aa++) { System.out.println(“Enter grade: ”); System.out.println(“Enter grade: ”); int grade = kbd.nextInt(); int grade = kbd.nextInt(); kbd.nextLine(); kbd.nextLine(); sum += grade; sum += grade;} S.o.pln(“Last assignment was ” + aa); OutOfScope.java:41: Cannot find symbol symbol : variable aa The “scope” of aa

45 Using Local Variables n Good idea if the variable is not supposed to be used outside a narrow context outside the grade reading loop, who needs to know any particular grade?outside the grade reading loop, who needs to know any particular grade? after counting to 6 (or whatever), who needs to know what number we’re on?after counting to 6 (or whatever), who needs to know what number we’re on? n If you need the variable after the loop, then you must declare it before the loop and if you don’t need it after, declare it inside!and if you don’t need it after, declare it inside!

46 On Doing One of Many Things n Can use cascading if controls to do exactly one of many things or at most one of many things (leave off else)or at most one of many things (leave off else) n switch control can sometimes be used if the one thing to do depends on the value of only one variable, and the values are constants:if the one thing to do depends on the value of only one variable, and the values are constants: if (var == 1) { } else if (var == 2 || var == 3) { } else if (var == 4) { …

47 Switch Control This: if (var == 1) { Sop(“One”); } else if (var == 2 || var == 3) { Sop(“2-3”); } else { Sop(“More”); } Becomes this: switch (var) { case 1: Sop(“One”); break; case 2: case 3: Sop(“2-3”); break; default: Sop(“More”); break; } One variable all the way down (var) (var == n) becomes case n: else becomes default break after every action

48 One Final Loop Type n In addition to while and for: do-while used when loop must iterate at least onceused when loop must iterate at least once all the data must be processedall the data must be processed know you’re done when processingknow you’re done when processing »example: add up numbers till get to 100 Sop(“Enter some numbers:”); do { num = kbd.nextInt(); num = kbd.nextInt(); sum += num; sum += num; } while (sum < 100); Sop(“Sum is ” + sum); Enter some numbers: 50 15 -10 34 13 Sum is 102

49 On switch and do-while n People planning to go on to 1228 should learn how to use them n People going on to 1227 (or stopping) only need to know they exist

50 Questions


Download ppt "Nested Structures Chapters 3 & 4. Outline n Conditionals inside loops n Conditionals inside conditionals n If-else-if controls n Loops inside loops n."

Similar presentations


Ads by Google