1 / 71

Chapter 4

Chapter 4. Control Structures Decisions Loops. Chapter 4 selection structures. This chapter begins a new path in our programming ability Basically we can cause our programs to follow different paths, react differently to different situations.

martinb
Télécharger la présentation

Chapter 4

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 4 • Control Structures • Decisions • Loops

  2. Chapter 4 selection structures • This chapter begins a new path in our programming ability • Basically we can cause our programs to follow different paths, react differently to different situations. • It’s an exciting time to be learning Java programming

  3. Chapter Overview • Control structures • Boolean expressions • If statements • Nested if • Switch • Looping

  4. Section 4.1 Control structures • Sequence • Selection • Alter normally sequential flow of a program • Repetition • Alter normally sequential flow of a program

  5. Boolean Expressions • Boolean has two possible values • True • False • Simplest Boolean expression is variable • boolean leapYear = true; • Can only be assigned true or false

  6. Relational operators • < less than • <= less than or equal • == equal • > greater than • >= greater than or equal • != not equal

  7. Reading Boolean data • Use JOptionPane.showConfirmDialog(null, “Is this fun?”); • This is the result of the statement • Returns 0 for yes, 1 for no, 2 for cancel

  8. Using the result • To convert this value to boolean simply use the result like this: • boolean myBool = (returnNum == 0) • See methods top of page 186 for method to handle this

  9. Operands • Operands can be: • Literals • Variables

  10. Boolean Operators • && and • || or • ! not

  11. And

  12. Or

  13. not

  14. Boolean Operators • (salary < minimumSalary) || (dependents > 5) • (temperature > 90.0) && (humidity > 0.90)

  15. Boolean variables in expressions • winningRecord && (!onProbation)

  16. Boolean Assignment • variable = expression • same = true; • same = (x == y);

  17. Short-circuit • Short circuit evaluation • Stops evaluating as soon as knows the outcome. • Can cause problems depending on what is in statement

  18. Writing Conditions • (min <= x) && (x <= max) x min max

  19. Comparing Characters • ‘c’ < ‘d’ true • ‘a’ > ‘A’ true • ‘3’ > ‘4’ false

  20. Comparing Strings • Must use String methods • string1.equals(string2)

  21. Lexicographic Comparison • string1.compareTo(string2) • Negative value if string 1 < string 2 • Value 0 if string 1 = string 2 • Positive value if string 1 > string 2 • See table pg 195

  22. gross > 100.00 net = gross - tax net = gross Section 4.3 if statement if (gross > 100.00) net = gross – tax; //if expression is true else net = gross; //if expression is false true false

  23. One selection if (x != 0.0) product = product * x;

  24. Syntax single selection • if (condition) statement;

  25. Syntax 2 alternatives if (condition) statement; else statement;

  26. Look at web example • http://faculty.juniata.edu/thomas/cs110/ifelse/Page1.htm

  27. If and compound statements • Use the braces to create a block of code in the if statement. if (x > y) { temp = x; x = y; y = temp; } //end if

  28. If else and compound • See example top page 200

  29. Returning booleans from methods • Look at example 4.8 page 201 • good way • need not do as shown on the bottom of the page

  30. 5.5 Decision steps in Algorithms • Decision step: selects one of several actions. • Review example 4.13 Pages 204-205

  31. Case Study page 205 • Payroll problem • Analysis • Design • Implementation • Page 213 variable scope • Local • Data fields

  32. 4.5 nested ifs • Besides using the Boolean operators && || and ! We can also create nested if statements. • Nested if statements are often more efficient than a sequence of if statements

  33. if (x > 0) y = y + 1; if (x < 0) y = y – 1; if (x ==0) y = y + 2; if (x> 0) y = y + 1; else if (x < 0) y = y – 1; else //btw x is 0 y = y + 2; Sequence versus Nested

  34. Matching else with If • You must use indentiation to make it clear how your if/else match. • BUT!! The compiler ignores the white space • Java matches each else with it’s closest preceding if that is not already matched with an else

  35. Good or Bad if (x > 0) y = y * 4; if (x < 0) y = y * - 4; else y = y + 4;

  36. Multiple alternative format if (score >= 90) displayResult(“A”); else if (score >= 80) displayResult(“B”); else if (score >= 70) displayResult(“C”); . .

  37. Example • Order matters big time see page 220 • Review tax example page 221

  38. Tips • Code nested ifs one statement at a time. • Code outer if then the internal ifs • TEST TEST TEST

  39. Switch statement • Switch allows you to select from several alternatives. • Works especially well when based on the value of one variable

  40. This is what it looks like switch (editOp) { case 0: search(); break; case 1: insert(); break; case 2: delete(); break; case 3: replace(); break; case 4: displayResult("All done"); break; default: displayResult("Invalid operation."); }

  41. Rules • The switch selector must be an ordinal data type. • Primitive • All values maybe listed • int, boolean, char • Not double • Break causes control to pass to statement after the switch. • Break statements are not always necessary

  42. Another example switch (month) { case 12 : julian = julian + day; case 11 : if (month == 11) julian = julian + day; else julian = julian + 30; case 10 : if (month == 10) julian = julian + day; else julian = julian + 31; case 9 : if (month == 9) julian = julian + day; else julian = julian + 30; case 1 : if (month == 1) julian = julian + day; else julian = julian + 31; }//end switch Case 8 – 2 go in here, slides just aren’t big enough

  43. Returning a value • Use of a return in a switch case statement also stops execution of the statement. • I am a little fussy with entry level programmers having multiple exit points in a method, although will allow it in a switch statement.

  44. Repetition Structures • In the programs we have written each line only executes at most 1 time. • There are times that we want statements to execute multiple times. • When would you want this? • Repetition is 3rd type of control structure • Sequence, selection, repetition

  45. Overview • Loops • Counting loops • Sentinel controlled loops • Flag controlled loops • Menu driven loops • Loop types • while • for • do-while

  46. Counting loops • Loop, repetition of steps in a program. • Counting loop repeats a predetermined number of times. • Name some real life examples of count controlled loops • Counter-controlled loops are controlled by a variable that keeps track of the number of repetitions performed.

  47. While statement • Syntax: while (condition) statement; • Statement is the body of the loop • Can be compound { } • Condition, continues looping while condition remains true

  48. Example int countTenSum = 1; int tenSum = 0 while (countTenSum < 11) { tenSum = tenSum + countTenSum; countTenSum = countTenSum + 1; }

  49. Example int numberEmp = readInt(“number of employees”); int countEmp = 0; while (countEmp < numberEmp) { //read pay data computer gross and net //add one to counter countEmp = countEmp + 1; }

  50. Syntax and formatting while (repetitionCondition) loopBody • Must use indentation for clarity • As in other cases white space is totally ignored by compiler

More Related