Nested Structures - PowerPoint PPT Presentation

nested structures n.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Nested Structures PowerPoint Presentation
Download Presentation
Nested Structures

play fullscreen
1 / 45
Nested Structures
151 Views
Download Presentation
Download Presentation

Nested Structures

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Nested Structures Chapters 3 & 4

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

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

  4. Loops with Conditionals • For each positive integer the user enters, say whether it’s divisible by 5 • stop 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 // get next number num = kbd.nextInt(); } kbd.nextLine();

  5. Expected Output • R(num) = read a number • D(num) = say num’s divisible by 5 • N(num) = say num’s not divisible by 5 Enter some numbers below: 10080 95788490 -1 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. R(100) D(100) R(80) D(80) R(95) D(95) R(78) N(78) R(84) N(84) R(95) D(95) R(-1) R(num), while (num >= 0): {(D(num) or N(num)), R(num)}.

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

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

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

  9. Exercise • Write a loop to read in six grades • print “Good work!” if that grade is 90+ • 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!

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

  11. 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!

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

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

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

  15. if inside if • You can put if controls inside if controls • if first condition is true, test second condition System.out.println(“A”); if (condition1) { System.out.println(“B”); if (condition2) { System.out.println(“C”); } } possible output:AABABC pattern:always Asometimes Bwhen B, sometimes C

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

  17. 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? ”); answer = kbd.nextLine().toLowerCase(); // if disabled, ask if live on own if (answer.startsWith(“y”)) { System.out.print(“Do you live on your own? ”); answer = kbd.nextLine().toLowerCase(); } eligible = answer.startsWith(“y”); }

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

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

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

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

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

  23. Cascading If Statements • Simplified conditions • already 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”); } What happens when age = 15? age is 25 Adult age is 65 Senior

  24. 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(); ... } else if (...) { 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

  25. Exercises • Write “Good morning” if time < 12, “Good afternoon” if 12  time < 17, “Good evening” otherwise • 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..5

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

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

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

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

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

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

  32. Exercise • What are the possible outputs of this code? System.out.print(“A”); if (…) { System.out.print(“B”); if (…) System.out.print(“C”); 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!

  33. Loops inside Loops • Draw four lines with 20 stars on each line • four lines all the same  a “for” loop • each line: • twenty stars, all the same  another “for” loop • line ends after the twenty stars • ******************** • ******************** • ******************** • ********************

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

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

  36. Loops inside Loops • 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 (int star = 1; star <= 20; ++star) { // print that star System.out.print(“*”); } // end that line (afterallthe stars) System.out.println(); }

  37. Inner and Outer Loops • One loop (inner) inside another (outer) // print a rectangle for (int line = 1; line <= height; line++) { // 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.

  38. Identify the Pieces and Patterns • Write nested loops to read numbers (integers) until a negative number is read • print 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

  39. Inner and Outer Loops Outer loop Inner loop Print out a given number of “Hello”s told number before start for loop: • Read numbers until a negative number is read • while loop: for (int i = 1; i <= num; ++i) { S.o.p.(“Hello! ”); } System.out.println(); 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(); } Change S.o.p. to System.out.print

  40. Identify the Pieces and Patterns • Write nested loops to read three valid assignment scores and calculate their average • 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%

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

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

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

  44. Using Local Variables • 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? • after counting to 6 (or whatever), who needs to know what number we’re on? • 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!

  45. Questions