Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University 1008 Wachman Hall, Main Campus Email: zhen.jiang@temple.edu 4/13/2015 1 Table of Contents 4/13/2015 Taste of decision-making If-else statement Relational (Boolean) Expression Complex Expression and Truth Table Development Process Multi-selection Other If statements Factoring Other materials Summary 2 Taste of decision making Rolling a dice. Sample execution (click on this link to try) Each button in the above sample has 4/13/2015 3 No Yes Win/Lost? Double the money Bankrupt Restart 4/13/2015 4 If-else Statement if/else statement: A control structure that executes one block of statements if a certain condition (checked by a Boolean expression) is true, and a second block of statements if it is false. We refer to each block as a branch. General syntax: if (<Boolean Expression>) { <statement(s)> ; } else { <statement(s)> ; } Example: if (gpa >= 3.0) { System.out.println("Welcome to Temple!"); } else { System.out.println("Try applying to Penn."); } 4/13/2015 5 No Boolean Expression Action 2 else controlled Yes Action 1 If controlled Action 3 4/13/2015 6 4/13/2015 7 Figure 3.1 The Action of the if-else Statement, p142 http://www.cis.templ e.edu/~jiang/BankBa lance.pdf 4/13/2015 8 4/13/2015 9 Relational (Boolean) Expression Relational expressions (p148) have numeric arguments and Boolean values. A simple expression uses one of the following six relational operators to check the relation of two values : Operator Meaning Example Value == equals 1 + 1 == 2 true != does not equal 3.2 != 2.5 true < less than 10 < 5 false > greater than 10 > 5 true <= less than or equal to 126 <= 100 false >= greater than or equal to 5.0 >= 5.0 true 4/13/2015 10 Lesson 3 (p148) !!! error: “(a=2)” instead of “(a==2)” 4/13/2015 11 Relational operators have lower precedence than math operators. 5 * 7 5 * 7 35 35 true >= >= >= >= 3 + 5 * (7 - 1) 3 + 5 * 6 3 + 30 33 Relational operators cannot be chained (unlike math operators) 2 <= x <= 10 error! 4/13/2015 12 The boolean type has two possible values: true and false boolean variables are declared and initialized just like other primitive data types: boolean iAmSoSmrt = false; System.out.print(iAmSoSmrt); boolean minor = (age < 21); 4/13/2015 //just like int i = 2; //print out ‘false’; //just like int x = y*2; 13 Complex Expression A complex Boolean expression is built out of simple expressions connected with logical operators. Logical operators have (p153) boolean arguments and boolean values Operator && Description and Example (9 != 6) && (2 < 3) Result true || or (2 == 3) || (-1 < 5) ! not !(7 > 0) true false 4/13/2015 14 Sub-expression S1 Sub-expression S2 S1 && S2 S1 || S2 !S1 True (T) T T T F (False) T F F T F F T F T T F F F F T 4/13/2015 15 What is the result of each of the following expressions? int x = 42; int y = 17; int z = 25; y < x && y <= z x % 2 == y % 2 || x % 2 == z % 2 x <= y + z && x >= y + z !(x < y && x < z) (x + y) % 2 == 0 || !((z - y) % 2 == 0) Answers: true, false, true, true, false 4/13/2015 16 You can compare char values with relational operators. 'a' < 'b' and 'Q' != 'q' Caution: You should NOT use these operators on a String! Example: // print the alphabet if(c>='a' && c<='z' && c>='A' && c<='Z') { //ASCII System.out.print(c); } 4/13/2015 17 Objects (such as String) should be compared for equality by calling a method named equals (P155). Example: Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); if (name.equals("Barney")) { System.out.println("I love you, you love me,"); System.out.println("We're a happy family!"); } 4/13/2015 18 There are more methods of a String object that can be used in <test> conditions. Method Description equals(str) whether this string contains exactly the same characters as the other string equalsIgnoreCase(str) whether this string contains the same characters as the other, ignoring uppervs. lowercase differences startsWith(str) whether this string’s beginning matches the argument endsWith(str) whether this string’s end matches the argument 4/13/2015 19 Hypothetical examples, assuming the existence of various String variables: if (title.endsWith("M.D.")) { System.out.println("What's your number?"); } if (fullName.startsWith("Giorgio")) { System.out.println("When are you retiring?"); } if (lastName.equalsIgnoreCase("lumBerg")) { System.out.println("I need your TPS reports!"); } if (name.toLowerCase().indexOf("sr.") >= 0) { System.out.println("You must be old!"); } 4/13/2015 20 Exercises 4/13/2015 Boolean expression 21 Development of a correct decision program 4/13/2015 Grade.java 22 Development Process Identify two exclusive options Implement each handling in different action parts Identify the situation (values) for option selection Make a boolean expression so that all situation values for option part 1 will lead to its evaluation true. Verify whether all situation values for option part 2 will lead to the evaluation of this expression in test false, otherwise, revise the above expression! 4/13/2015 23 Exercise of simple expression development 4/13/2015 Correct use of relational operator Development of a complete expression 25 Multiple Selection Concepts 4/13/2015 Nested if, p158 Multibranch If-else, p160 26 Idea of multiple selection If case 1 Else if case 2 else … //end of case 2 if //End of case 1 if 4/13/2015 27 Example 1 Pass/fail => Excellent/pass/fail More cases, p164 http://www.cis.temple.edu/~jiang/Grader.pdf 4/13/2015 28 Example 2 15% tip of a meal, with the minimum $1, but cannot exceed the amount of the meal itself. Case 1? Case 2? Case 3? 4/13/2015 29 Other if statements if statement: A control structure that executes a block of statements only if a certain condition is true. General syntax: if (<test>) { <statement(s)> ; } Example (with grade inflation): if (gpa >= 2.0) { System.out.println("You get an A!"); } 4/13/2015 30 4/13/2015 31 Chained if/else statement (also called mulit-branch if statement): A chain of if/else that can select between many different outcomes based on several tests. General syntax: if (<test>) { <statement(s)> ; } else if (<test>) { <statement(s)> ; } else { <statement(s)> ; } Example: if (number > 0) { System.out.println("Positive"); } else if (number < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); } 4/13/2015 32 if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else { <statement(s)>; } 4/13/2015 33 if (<test>) { <statement(s)>; } if (<test>) { <statement(s)>; } if (<test>) { <statement(s)>; } 4/13/2015 34 A chained if/else can end with an if or an else. If it ends with else, one of the branches must be taken. If it ends with if, the program might not execute any branch. if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else { <statement(s)>; } 4/13/2015 if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } 35 if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else { <statement(s)>; } 4/13/2015 36 if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } else if (<test>) { <statement(s)>; } 4/13/2015 37 Scope scope: The portion of a program where a given variable exists. A variable's scope is from its declaration to the end of the { } braces in which it was declared. public class ScopeExample { public static void main(String[] args) { int x = 3; int y = 7; if(x > 0 && y > 0) { int sumPositives = x + y; } else { sumPositives = 0; // illegal: sumPositives is out of scope } // illegal: sumPositives is out of scope System.out.println("sum = " + sumPositives); } Why not just have the scope of a variable be the whole program? 4/13/2015 38 String message; if (gpa >= 3.0) { message = "Welcome to Temple!"; } if (gpa >= 2.0) { message = "Have you considered applying to Penn?"; } if (gpa < 2.0) { message = "I hear Harvard still needs students..."; } System.out.println(message); The compiler will complain that "variable message might not have been initialized". Why? 4/13/2015 39 The solution: String message; if (gpa >= 3.0) { message = "Welcome to Temple!"; } else if (gpa >= 2.0) { message = "Have you considered applying to Penn?"; } else { // gpa < 2.0 message = "I hear Harvard still needs students..."; } System.out.println(message); 4/13/2015 40 Factoring if/else factoring: extracting common/redundant code Factoring if/else code reduces the size of the if and else statements Factoring tips: If the start of each branch is the same, move it before the if/else. If the end of each branch is the same, move it after the if/else. 4/13/2015 41 if (money < 500) { System.out.println("You have, $" + money + " left."); System.out.print("Caution! Bet carefully."); System.out.print("How much do you want to bet? "); bet = console.nextInt(); } else if (money < 1000) { System.out.println("You have, $" + money + " left."); System.out.print("Consider betting moderately."); System.out.print("How much do you want to bet? "); bet = console.nextInt(); } else { System.out.println("You have, $" + money + " left."); System.out.print("You may bet liberally."); System.out.print("How much do you want to bet? "); bet = console.nextInt(); } 4/13/2015 42 System.out.println("You have, $" + money + " left."); if (money < 500) { System.out.print("Caution! Bet carefully."); } else if (money < 1000) { System.out.print("Consider betting moderately."); } else { System.out.print("You may bet liberally."); } System.out.print("How much do you want to bet? "); bet = console.nextInt(); 4/13/2015 43 4/13/2015 44 Multiple Selection Exercise 4/13/2015 45 Other materials (reading materials) Conditional Operator (P168) ( Boolean Expression)? <value1> :<value 2>; Precedence Rules (P172) Input & Output of Boolean Variables (P174) Switch (P176-180) 4/13/2015 Switch([variable]) Case [constant value]: Break (or no break), p180 46 Summary BankBalance.java, p142 Grader.java, p164 Exercises, slides 21, 25, 45 4/13/2015 47 4/13/2015 Boolean Expression and its evaluation (P148-157, P86) Precedence Rule (P172) Input & output of boolean variables (P174) If-else statement (P144) and If statement (P145) Development of If-else or If statement (5 phase development) Action factoring Development of multiple choice selection Nested if (P158) and Multi-branch if statement (P160) Conditional operator (P168) Scope Switch (P176) 48