1 / 91

Chapter 4 Selection Control Statements

Chapter 4 Selection Control Statements. The if Statement More About Selection Errors Testing and Debugging Artificial Intelligence. The if Statement. Making a decision. The if Statement. The if Statement. Relational Operators with if. Relational operator: compares two values

tyler-mejia
Télécharger la présentation

Chapter 4 Selection Control Statements

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 4Selection Control Statements The if Statement More About Selection Errors Testing and Debugging Artificial Intelligence

  2. The if Statement • Making a decision Programming and Problem Solving With Java

  3. The if Statement Programming and Problem Solving With Java

  4. The if Statement Programming and Problem Solving With Java

  5. Relational Operators with if • Relational operator: compares two values • Relational operators in Java • Notice!! Test for equality is == Programming and Problem Solving With Java

  6. Turtle Graphics Constants • Makes if statements more readable • if (Turtle.MAX_ROW - myTurtle.atRow() < 10) • { • myTurtle.turnRight(180); • } Programming and Problem Solving With Java

  7. Methods that Provide Turtle Info Programming and Problem Solving With Java

  8. Relational Operands: Primitives • Compare two primitive values • Value of type byte, int, short, long, float, … • Relational operator tells how the values compare • Example • if (3 < 5) … • 3 and 5 are integers • 3 is less than 5, so condition is true Programming and Problem Solving With Java

  9. Relational Operands: Objects • Compare two objects • Object of class String, Turtle, … • Relational operator compares objects, not their values • Example • String message1 = "Hi there"; • String message2 = "Hi " + "there"; • if (message1 == message2) • { • System.out.println("The messages are the same"); • } • if (message1 != message2) • { • System.out.println("The messages are different"); • } • message1 and message2 refer to different objects message1 Hi there message2 Hi there false displays true Programming and Problem Solving With Java

  10. String Methods: compareTo() • a.compareTo(b) returns • 0 if a == b • < 0 if a < b • > 0 if a > b • Example • String a = " Hi there"; • String b = " HI THERE"; • if (a.compareTo(b) == 0) • { • System.out.println("Yes"); • } • No output: a and b have different values Programming and Problem Solving With Java

  11. String Methods: endsWith() • a.endsWith(b) returns • true if the last characters in a are b • false otherwise • Example • String a = " Hi there"; • if(a.endsWith("ere")) • { • System.out.println("Yes"); • } • Displays Yes: the last threecharacters of a are "ere" Programming and Problem Solving With Java

  12. Strings: equals() • a.equals(b) returns • true if the values of a and b are the same • false otherwise • Example • String a = " Hi there"; • String b = " HI THERE"; • if(a.equals(b)) • { • System.out.println("Yes"); • } • Displays nothing: a and b have the different values (upper and lower case letters are different characters) Programming and Problem Solving With Java

  13. Strings: equalsIgnoreCase() • a.equalsIgnoreCase(b) returns • true if the values of a and b are the same, regardless of upper and lower case differences • false otherwise • Example • String a = " Hi there"; • String b = " HI THERE"; • if(a.equalsIgnoreCase(b)) • { • System.out.println("Yes"); • } • Displays Yes: a and b have the same values (ignoring case) Programming and Problem Solving With Java

  14. String Methods: startsWith() • a.startsWith(b) returns • true if the first characters in a are b • false otherwise • Example • String a = " Hi there"; • if(a.startsWith(" Hi")) • { • System.out.println("Yes"); • } • Displays Yes: the first four characters of a are " Hi" (two spaces at beginning) Programming and Problem Solving With Java

  15. The char Type • Used for storing single characters • Literal values surrounded by single quotes • 'A' 'a' '?' '9' '!' • Displaying a character • System.out.println('B'); • Upper and lower case characters are different • 'a' != 'A' Programming and Problem Solving With Java

  16. The if Statement: char Enter first integer: 23 Enter second integer: 42 Enter A to add the numbers, M to multiply them: A The sum is 65 • char choice; • int firstNum, secondNum; • // Ask user for first number • firstNum = Keyboard.readInt("Enter first integer: "); • // Ask user for second number • secondNum = Keyboard.readInt("Enter second integer: "); • // Ask user which operation to use • choice = Keyboard.readChar("Enter A to add the numbers, " • + "M to multiply them: "); • // Display the results • if (choice == 'A') • { • System.out.println("The sum is " • + (firstNum + secondNum)); • } • if (choice == 'M') • { • System.out.println("The product is " • + (firstNum * secondNum)); • } Programming and Problem Solving With Java

  17. The readChar() Method • Three ways to use readChar() • No prompt message • choice = Keyboard.readChar(); • Prompting message • choice = Keyboard.readChar("Enter A to add the numbers, " • + "M to multiply them: "); • Prompting message and restricted input • choice = Keyboard.readChar("Enter A to add the numbers, " • + "M to multiply them: ", "AM"); Enter A to add the numbers, M to multiply them: X Please enter one of these characters: AM Enter A to add the numbers, M to multiply them: G Please enter one of these characters: AM Enter A to add the numbers, M to multiply them: A Programming and Problem Solving With Java

  18. Comparing Characters • Computercompares Unicode values of characters • if ('A' < 'B') ... • Unicode value of'A' is 65 • Unicode value of'B' is 66 • 'A' < 'B' becomes65 < 66 Programming and Problem Solving With Java

  19. Compound Statements • Compound statement: one or more statements surrounded by braces • { • x++; • System.out.print("Hello"); • } • Compiler treats as a single statement • if statement operates on a single statement • if (condition) if (myTurtle.direction() > 180) • statement myTurtle.move(100); No braces! Programming and Problem Solving With Java

  20. if with Compound Statements • Must use compound statement if more than one • if (condition) if (myTurtle.direction() > 180) • { { • statement1 myTurtle.move(100); • statement2 myTurtle.turnRight(90); • } } • Good programming practice: always use compound statement with if • Shows structure more clearly • Can easily add statements to if-body • Avoid dangling-else problem (coming up shortly) Programming and Problem Solving With Java

  21. The else Clause • else clause an optional part of if statement • Computer executes one of 2 statements • if (condition) • { • statements • } • else • { • statements • } • If condition is true, execute if-body • Otherwise, else-body Programming and Problem Solving With Java

  22. The else Clause Programming and Problem Solving With Java

  23. The else Clause: turn() Method • turn() method for turtle that turns 0 - 360o • Approach • If the angle is 180 or less, do single turnRight(). • Otherwise, do turnRight(180), then turnRight the rest • // turn: Turn to the right, from 0 to 360 degrees • public void turn(int degrees) • throws TurtleException • { • if (degrees <= 180) • { • this.turnRight(degrees); • } • else • { • this.turnRight(180); • this.turnRight(degrees - 180); • } • } Programming and Problem Solving With Java

  24. Nested if Statements • Nested decision: Onedecision depends on the result of another Programming and Problem Solving With Java

  25. Nested if Statements • Example: Cost of first-class letter • 40 cents for first ounce, 30 cents for each additional • Must be between 1 and 11 ounces • After reading weight • if (weight > 0) // Outer-if statement • { • if (weight <= FIRST_CLASS_LIMIT) // Inner-if statement • { • costInCents = FIRST_OUNCE_COST • + ADDITIONAL_OUNCE_COST * (weight - 1); • System.out.println("Cost: " + costInCents + " cents"); • } • else • { • System.out.println("Use parcel post or priority mail"); • } • } • else • { • System.out.println("ERROR: Weight must be positive"); • } Programming and Problem Solving With Java

  26. Dangling-else Problem • Arises only with nested if statements without braces • Example • // For a score less than 70, displays "You need to improve" • // For a score greater than 95, displays "Excellent work" • // For a score between 70 and 95, displays nothing • if (testScore >= 70) // Outer-if statement • if (testScore > 95) // Inner-if statement • System.out.println("Excellent work!"); • else • System.out.println("You need to improve"); • Results Programming and Problem Solving With Java

  27. Dangling-else Problem • When compiler finds else clause • "The else always matches the closest, unfinished if statement" • // For a score less than 70, displays "You need to improve" • // For a score greater than 95, displays "Excellent work" • // For a score between 70 and 95, displays nothing • if (testScore >= 70) // Outer-if statement • if (testScore > 95) // Inner-if statement • System.out.println("Excellent work!"); • else • System.out.println("You need to improve"); Programming and Problem Solving With Java

  28. Dangling-else Problem • Structure of a dangling else clause Programming and Problem Solving With Java

  29. Dangling-else Problem • How bracesavoid thedangling-elseproblem Programming and Problem Solving With Java

  30. Multiway Choices Programming and Problem Solving With Java

  31. char grade; if (score >= 90) { grade = 'A'; } else { if (score >= 80) { grade = 'B'; } else { if (score >= 70) { grade = 'C'; } else { if (score >= 60) { grade = 'D'; } else { grade = 'F'; } } } } char grade; if (score >= 90) { grade = 'A'; } else if (score >= 80) { grade = 'B'; } else if (score >= 70) { grade = 'C'; } else if (score >= 60) { grade = 'D'; } else { grade = 'F'; } Multiway Choices: if-ladder if-ladder Nested if rewrite nested if as if-ladder Programming and Problem Solving With Java

  32. How the if-ladder Works Programming and Problem Solving With Java

  33. Multiway Choices: if-ladder • Default condition: last else in if-ladder • · Optional • Good idea to have one -- helps catch errors • if (score >= 90) • { • grade = 'A'; • } • else if (score >= 80) • { • grade = 'B'; • } • else if (score < 60) • { • grade = 'F'; • } • else • { • System.out.println("Error in assignGrade"); • } Missing cases for grades of C and D Default condition catches the error Programming and Problem Solving With Java

  34. General face() Method • Turtle graphics turnRight() -- turns relative degrees • No method to make turtle face absolute direction • Can use nested if to write face() • myTurtle.face(122); • Direction of turtle can be anything • face(122) makes turtle face 122 degrees Programming and Problem Solving With Java

  35. General face() Method • Three cases to consider (c) The turtle may already be facing the desired direction Programming and Problem Solving With Java

  36. General face() Method • Three cases  need nested if statement • First version of face() • Handle case where turtle already facing desired direction • // face: Faces the turtle an absolute direction, • // from 1 to 360 degrees • public void face(int degrees) • throws TurtleException • { • // Make sure the turtle is not already facing the desired • // direction • if (this.direction() != degrees) • { • // Handle the other two cases here • } • } • Must distinguish between the remaining two cases Programming and Problem Solving With Java

  37. General face() Method • Distinguish between two cases Current Direction > Desired Direction Current Direction < Desired Direction Programming and Problem Solving With Java

  38. General face() Method • Doesn't cross 0, current direction < desired • Second version of face() • // face: Faces the turtle an absolute direction, • // from 1 to 360 degrees • public void face(int degrees) • throws TurtleException • { • // Make sure the turtle is not already facing the desired • // direction • if (this.direction() != degrees) • { • if (this.direction() < degrees) • { • // The turtle doesn't cross 0 • this.turn(degrees - this.direction()); • } • else • { • // The turtle crosses 0 • } • } • } Programming and Problem Solving With Java

  39. General face() Method • Crosses 0, current direction > desired • Turn in two steps Programming and Problem Solving With Java

  40. General face() Method • Final version of face() • // face: Faces the turtle an absolute direction, • // from 1 to 360 degrees • public void face(int degrees) • throws TurtleException • { • // Make sure the turtle is not already facing the desired • // direction • if (this.direction() != degrees) • { • if (this.direction() < degrees) • { • // The turtle doesn't cross 0 • this.turn(degrees - this.direction()); • } • else • { • // The turtle crosses 0 • this.turn(360 - this.direction() + degrees); • } • } • } Programming and Problem Solving With Java

  41. goPosition(): Example of if • Turtle graphics move() -- moves relative distance • No method to make turtle move to absolute position • Can use nested if to write goPosition() • myTurtle.goPosition(10, 20); // row 10, column 20 • Turtle can be anywhere on screen • Will move to upper left corner(facing same direction) Programming and Problem Solving With Java

  42. goPosition(): Example of if • Use helper methods • moveToRow() • moveToColumn(); • First version of goPosition() • // goPosition: Moves turtle to any absolute position on the • // screen, without drawing a line. The • // direction and pen status are unchanged. • public void goPosition(int row, int column) • throws TurtleException • { • this.moveToRow(row); • this.moveToColumn(column); • } Programming and Problem Solving With Java

  43. goPosition(): Example of if • Want pen status to be unchanged • Second version of goPosition() • // goPosition: Moves turtle to any absolute position on the • // screen, without drawing a line. The • // direction and pen status are unchanged. • public void goPosition(int row, int column) • throws TurtleException • { • // Remember previous pen status • boolean penDownAtBeginning = this.isPenDown(); • if (this.isPenDown()) • { • this.penUp(); • } • this.moveToRow(row); • this.moveToColumn(column); • // Put pen back down if it was down before • if (penDownAtBeginning) • { • this.penDown(); • } • } Programming and Problem Solving With Java

  44. goPosition(): Example of if • Also want direction to be unchanged • Final version of goPosition() • // goPosition: Moves turtle to any absolute position on the • // screen, without drawing a line. The • // direction and pen status are unchanged. • public void goPosition(int row, int column) • throws TurtleException • { • // Remember previous pen status and direction • boolean penDownAtBeginning = this.isPenDown(); • int previousDirection = this.direction(); • if (this.isPenDown()) • { • this.penUp(); • } • this.moveToRow(row); • this.moveToColumn(column); • // Put pen back down if it was down before • if (penDownAtBeginning) • { • this.penDown(); • } • // Restore previous direction • this.face(previousDirection); • } Programming and Problem Solving With Java

  45. goPosition(): Example of if • Need to write moveToRow(), moveToColumn() • Three cases in moveToRow() Programming and Problem Solving With Java

  46. goPosition(): Example of if • moveToRow(): Do nothing if already on desired row • First version of moveToRow() • // moveToRow: Moves the turtle to an absolute row number. • // Pen must be up beforehand, and is left • // up afterward. The turtle's direction is • // changed. • // (This is a private method.) • private void moveToRow(int row) • throws TurtleException • { • // Make sure not on desired row • if (row != this.atRow()) • { • // Handle the other two cases • } • } Programming and Problem Solving With Java

  47. goPosition(): Example of if • moveToRow(): Use atRow() to tell direction to move • Second version of moveToRow() • // moveToRow: Moves the turtle to an absolute row number. • // Pen must be up beforehand, and is left • // up afterward. The turtle's direction is • // changed. • // (This is a private method.) • private void moveToRow(int row) • throws TurtleException • { • // Make sure not on desired row • if (row != this.atRow()) • { • // Handle the other two cases • if (row < this.atRow()) • { • // Turtle below desired row • } • else • { • // Turtle above desired row • } • } • } Programming and Problem Solving With Java

  48. goPosition(): Example of if • movePosition(): turtle is below desired row • Use face() to turn turtle straight up • Move from current row to desired row • this.face(0); • this.move(this.atRow() - row); • movePosition(): turtle is above desired row • Use face() to turn turtle straight down • Move from current row to desired row • this.face(180); • this.move(row - this.atRow()); Desired row Programming and Problem Solving With Java

  49. goPosition(): Example of if • Final version of moveToRow() • // moveToRow: Moves the turtle to an absolute row number. • // Pen must be up beforehand, and is left • // up afterward. The turtle's direction is • // changed. • // (This is a private method.) • private void moveToRow(int row) • throws TurtleException • { • // Make sure not on desired row • if (row != this.atRow()) • { • // Handle the other two cases • if (row < this.atRow()) • { • // Turtle below desired row • this.face(0); • this.move(this.atRow() - row); • } • else • { • // Turtle above desired row • this.face(180); • this.move(row - this.atRow()); • } • } • } Programming and Problem Solving With Java

  50. Boolean Operators & Expressions • Decisions often based on more than one factor • I will buy a new shirt if I like it AND it costs less than $25. • I will study in my room tonight if it's quiet there OR the library is closed. • Compound conditions in English • condition1 AND condition2 • condition1 OR condition2 • NOT condition AND OR NOT Programming and Problem Solving With Java

More Related