Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 10/27/20151
Table of Contents 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 10/27/20152
Rolling a dice. Sample execution (click on this link to try)this link Each button in the above sample has Taste of decision making 10/27/20153
Win/Lost? Yes Double the money Bankrupt No Restart 10/27/20154
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 ( ) { ; } else { ; } Example: if (gpa >= 3.0) { System.out.println("Welcome to Temple!"); } else { System.out.println("Try applying to Penn."); } If-else Statement 10/27/20155
Boolean Expression Yes Action 1 If controlled Action 2 else controlled No Action 3 10/27/20156
7
Figure 3.1 The Action of the if-else Statement, p142 ~jiang/BankBalance.pdf ~jiang/BankBalance.pdf 10/27/20158
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 : true5.0 >= 5.0 greater than or equal to >= false126 <= 100 less than or equal to <= true10 > 5 greater than > false10 < 5 less than < true3.2 != 2.5 does not equal != true1 + 1 == 2 equals == ValueExampleMeaningOperator 10/27/201510
Lesson 3 (p148) !!! error: “(a=2)” instead of “(a==2)” 10/27/201511
Relational operators have lower precedence than math operators <= x 5 <= x Relational operators cannot be chained (unlike math operators) 2 <= x <= 10 error! 10/27/201512
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; //just like int i = 2; System.out.print(iAmSoSmrt); //print out ‘false’; boolean minor = (age < 21); //just like int x = y*2; 10/27/201513
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 (9 != 6) && (2 > 3) (9 != 6) || (2 > 3) ! (2 > 3) Example not or and Description ! || false&& ResultOperator 10/27/ true
Sub-expression S1Sub-expression S2S1 && S2S1 || S2!S1 True (T)TTTF (False) TFFTF FTFTT FFFFT 10/27/201515
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 && x < z) (x + y) % 2 == 0 || !((z - y) % 2 == 0) Answers: true, false, true, true, false 10/27/201516
17 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 ='A' && c<='Z') { //ASCII System.out.print(c); } 10/27/2015
18 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!"); } 10/27/2015
19 There are more methods of a String object that can be used in conditions. whether this string’s beginning matches the argument startsWith(str) whether this string’s end matches the argument endsWith(str) whether this string contains the same characters as the other, ignoring upper- vs. lowercase differences equalsIgnoreCase(str) whether this string contains exactly the same characters as the other string equals(str) DescriptionMethod 10/27/2015
20 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!"); } 10/27/2015
Exercises Boolean expression 10/27/201521
Development of a correct decision program Grade.java 10/27/201522
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! Development Process 10/27/201523
Exercise of simple expression development Correct use of relational operator Development of a complete expression 10/27/201525
Concepts Nested if, p158 Multibranch If-else, p160 Multiple Selection 10/27/201526
Idea of multiple selection If case 1 Else if case 2 else … //end of case 2 if //End of case 1 if 10/27/201527
10/27/201528
Example 1 Passed/failed => Excellent/passed/failed More cases, p /27/201529
Example 2 15% tip of a meal, with the minimum $1, but cannot exceed the amount of the meal price itself. Case 1? Case 2? Case 3? 10/27/201530
Other if statements if statement: A control structure that executes a block of statements only if a certain condition is true. General syntax: if ( ) { ; } Example (with grade inflation): if (gpa >= 2.0) { System.out.println("You get an A!"); } 10/27/201531
10/27/201532
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 ( ) { ; } else if ( ) { ; } else { ; } Example: if (number > 0) { System.out.println("Positive"); } else if (number < 0) { System.out.println("Negative"); } else { System.out.println("Zero"); } 10/27/201533
if ( ) { ; } else if ( ) { ; } else { ; } 10/27/201534
if ( ) { ; } if ( ) { ; } if ( ) { ; } 10/27/201535
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 ( ) { ; } else if ( ) { ; } else { ; } if ( ) { ; } else if ( ) { ; } else if ( ) { ; } 10/27/201536
if ( ) { ; } else if ( ) { ; } else { ; } 10/27/201537
if ( ) { ; } else if ( ) { ; } else if ( ) { ; } 10/27/201538
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? 10/27/201539
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? 10/27/201540
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); 10/27/201541
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. 10/27/201542
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(); } 10/27/201543
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(); 10/27/201544
Multiple Selection Exercise 10/27/201545
Conditional Operator (P168) ( Boolean Expression)? : ; Precedence Rules (P172) Input & Output of Boolean Variables (P174) Switch (P ) Switch([variable]) Case [constant value]: Break (or no break), p180 Other materials (reading materials) 10/27/201546
BankBalance.java, p142 Grader.java, p164 Exercises, slides 21, 25, 45 Summary 10/27/201547
Boolean Expression and its evaluation (P , 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) 10/27/201548