Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University...

48
Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: [email protected] 03/27/22 1

Transcript of Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University...

Decision Making - CIS 1068 Program Design and Abstraction

Zhen Jiang

CIS Dept.

Temple University

SERC 347, Main Campus

Email: [email protected]

04/20/23 1

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

04/20/23 2

Rolling a dice. Sample execution (click on this link to

try) Each button in the above sample has

Taste of decision making

04/20/23 3

Win/Lost?Yes

Double themoney

Bankrupt

No

Restart

04/20/23 4

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.");}

If-else Statement

04/20/23 5

Boolean Expression

Yes

Action 1If controlled

Action 2else controlled

No

Action 3

04/20/23 6

04/20/23 7

Figure 3.1 The Action of the if-else Statement, p142

http://www.cis.temple.edu/~jiang/BankBalance.pdf

04/20/23 8

04/20/23 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.0greater than or equal to>=

false126 <= 100less than or equal to<=

true10 > 5greater than>

false10 < 5less than<

true3.2 != 2.5does not equal!=

true1 + 1 == 2equals==

ValueExampleMeaningOperator

04/20/23 10

Lesson 3 (p148) !!! error: “(a=2)” instead of “(a==2)”

04/20/23 11

Relational operators have lower precedence than math operators.

2 + 3 <= x 5 <= x

Relational operators cannot be chained (unlike math operators)

2 <= x <= 10error!

04/20/23 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; //just like int i = 2;

System.out.print(iAmSoSmrt); //print out ‘false’;

boolean minor = (age < 21); //just like int x = y*2;04/20/23 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

(9 != 6) && (2 > 3)

(9 != 6) || (2 > 3)

! (2 > 3)

Example

not

or

and

Description

!

||

false&&

ResultOperator

04/20/23 14

true

true

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

04/20/23 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, false04/20/23 16

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 alphabetif(c>='a' && c<='z’ || c>='A' && c<='Z') { //ASCII System.out.print(c);

}

04/20/23

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!");

}

04/20/23

19

There are more methods of a String object that can be used in <test> 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

04/20/23

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!");}

04/20/23

Exercises Boolean expressionhttp://www.cis.temple.edu/~jiang/

1068TracingDecision.pdf

04/20/23 21

Development of a correct decision program Grade.java

04/20/23 22

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

04/20/23 23

Exercise of simple expression development Correct use of relational operatorhttp://www.cis.temple.edu/~jiang/

1068simpleExpression.pdf

Development of a complete expression

http://www.cis.temple.edu/~jiang/1068simpleExpression2.pdf

04/20/23 25

Concepts Nested if, p158 Multibranch If-else, p160

Multiple Selection

04/20/23 26

Idea of multiple selectionIf

case 1Else

if case 2

else…

//end of case 2 if//End of case 1 if

04/20/23 27

04/20/23 28

Example 1 Passed/failed =>

Excellent/passed/failed More cases, p164 http://www.cis.temple.edu/~jiang/

Grader.pdf

04/20/23 29

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?

04/20/23 30

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!");}04/20/23 31

04/20/23 32

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");}

04/20/23 33

if (<test>) { <statement(s)>;} else if (<test>) { <statement(s)>;} else { <statement(s)>;}

04/20/23 34

if (<test>) { <statement(s)>;}if (<test>) { <statement(s)>;}if (<test>) { <statement(s)>;}

04/20/23 35

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)>;}

if (<test>) { <statement(s)>;} else if (<test>) { <statement(s)>;} else if (<test>) { <statement(s)>;}

04/20/23 36

if (<test>) { <statement(s)>;} else if (<test>) { <statement(s)>;} else { <statement(s)>;}

04/20/23 37

if (<test>) { <statement(s)>;} else if (<test>) { <statement(s)>;} else if (<test>) { <statement(s)>;}

04/20/23 38

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?

04/20/23 39

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?

04/20/23 40

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);

04/20/23 41

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.

04/20/23 42

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();}

04/20/23 43

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();

04/20/23 44

Multiple Selection Exercisehttp://www.cis.temple.edu/~jiang/1068multiSelection.pdf

04/20/23 45

Conditional Operator (P168) ( Boolean Expression)? <value1> :<value

2>; Precedence Rules (P172) Input & Output of Boolean Variables

(P174) Switch (P176-180)

Switch([variable]) Case [constant value]: Break (or no break), p180

Other materials (reading materials)

04/20/23 46

BankBalance.java, p142 Grader.java, p164 Exercises, slides 21, 25, 45

Summary

04/20/23 47

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)

04/20/23 48