Chapter 5 Decisions Chapter 5 Decisions 1 Chapter

  • Slides: 64
Download presentation
Chapter 5 Decisions Chapter 5 Decisions 1

Chapter 5 Decisions Chapter 5 Decisions 1

Chapter Goals q To be able to implement decisions using if statements q To

Chapter Goals q To be able to implement decisions using if statements q To understand how to group statements into blocks q q q To learn how to compare integers, floating-point numbers, strings and objects To recognize the correct ordering of decisions in multiple branches To program conditions using Boolean operators and variables Chapter 5 Decisions 2

The if Statement q The if statement lets a program carry out different actions

The if Statement q The if statement lets a program carry out different actions depending on a condition if (amount <= balance) balance = balance - amount; Chapter 5 Decisions 3

The if Statement Figure 1: Flowchart for an if statement Chapter 5 Decisions 4

The if Statement Figure 1: Flowchart for an if statement Chapter 5 Decisions 4

The if/else Statement q Why doesn’t this work? if (amount balance q <= balance)

The if/else Statement q Why doesn’t this work? if (amount balance q <= balance) = balance - amount; > balance) = balance - OVERDRAFT_PENALTY; Use if/else to choose between alternatives if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY; Chapter 5 Decisions 5

The if/else Statement Figure 2: Flowchart for an if/else statement Chapter 5 Decisions 6

The if/else Statement Figure 2: Flowchart for an if/else statement Chapter 5 Decisions 6

Statement Types q Simple statement balance = balance - amount; q Compound statement if

Statement Types q Simple statement balance = balance - amount; q Compound statement if (balance >= amount) balance = balance - amount; q Other examples in Java: while, for, etc. (loop statements, discussed in Chapter 7) Chapter 5 Decisions 7

Statement Types q Block statement: enclose multiple simple statements in { … } {

Statement Types q Block statement: enclose multiple simple statements in { … } { double new. Balance = balance - amount; balance = new. Balance; } q For example if (amount <= balance) { double new. Balance = balance - amount; balance = new. Balance; } Chapter 5 Decisions 8

Syntax 6. 1: The if Statement if(condition) statement if (condition) statement 1 else statement

Syntax 6. 1: The if Statement if(condition) statement if (condition) statement 1 else statement 2 Example: if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY; Purpose: To execute a statement when a condition is true or false Chapter 5 Decisions 9

Syntax 6. 2: Block Statement { statement 1 statement 2. . . } Example:

Syntax 6. 2: Block Statement { statement 1 statement 2. . . } Example: { double new. Balance = balance - amount; balance = new. Balance; } Purpose: To group several statements together to form a single statement Chapter 5 Decisions 10

Brace Layout q Compiler doesn’t care how braces align if (amount <= balance){ double

Brace Layout q Compiler doesn’t care how braces align if (amount <= balance){ double new. Balance = balance - amount; balance = new. Balance; } q For human readability, make braces line up if (amount <= balance) { double new. Balance = balance - amount; balance = new. Balance; } q Good idea to use braces for all if statements Chapter 5 Decisions 11

Brace Layout q In fact, for the code you write in this class, you

Brace Layout q In fact, for the code you write in this class, you must use braces with all if statements § Even if braces not required by Java syntax q q For example, this is good… if (amount <= balance) { double new. Balance = balance - amount; } But this will lose points… if (amount <= balance) double new. Balance = balance - amount; Chapter 5 Decisions 12

Brace Layout q You must also be able to read code when braces are

Brace Layout q You must also be able to read code when braces are not used with if statements § Since braces not always required by Java syntax q In slides and book, braces are often omitted q But always use braces in if statements for code you write in this class § Got it? Chapter 5 Decisions 13

Self-Check 1. Why did we use the condition amount <= balance and not <

Self-Check 1. Why did we use the condition amount <= balance and not < balance in if/else example? 2. What is wrong with the statement amount if (amount <= balance) new. Balance = balance - amount; balance = new. Balance; and how can you fix it? Is this a logic or syntax error? Chapter 5 Decisions 14

Answers 1. If the withdrawal amount equals the balance, the result should be a

Answers 1. If the withdrawal amount equals the balance, the result should be a zero balance and no penalty 2. Only the first assignment statement is part of the if statement. Use braces to group both assignment statements into a block statement. It is a logic error. Chapter 5 Decisions 15

Selection Operator q A shorthand way to do if/else condition ? value 1 :

Selection Operator q A shorthand way to do if/else condition ? value 1 : value 2 § value 1 result of “if” § value 2 result of “else” q For example can be used in place of if/else construct y = x >= 0 ? x : -x; if(x >= 0) y = x; else y = -x; Chapter 5 Decisions 16

Comparing Values: Relational Operators q q Relational operators compare values Java Math Notation Description

Comparing Values: Relational Operators q q Relational operators compare values Java Math Notation Description > > Greater than >= ≥ Greater than or equal < < Less than <= ≤ Less than or equal == = Equal != ≠ Not equal The == operator denotes equality testing a = 5; // Assign 5 to a if (a == 5). . . // Test whether a equals 5 Chapter 5 Decisions 17

Comparing Values: Relational Operators q “==“ often leads to errors q For example a

Comparing Values: Relational Operators q “==“ often leads to errors q For example a = 5; // Assign 5 to a if (a = 5). . . // what happens here? q This is probably what was intended a = 5; // Assign 5 to a if (a == 5). . . // Test whether a == 5 Chapter 5 Decisions 18

Comparing Floating-Point Numbers q Consider the code double r = Math. sqrt(2); double d

Comparing Floating-Point Numbers q Consider the code double r = Math. sqrt(2); double d = r * r - 2; if (d == 0) System. out. println("sqrt(2)squared minus 2 is 0"); else System. out. println("sqrt(2)squared minus 2 not 0 but " + d); q This code prints sqrt(2)squared minus 2 is not 0 but 4. 440892098500626 E-16 Chapter 5 Decisions 19

Comparing Floating-Point Numbers q q To avoid roundoff errors, do not use == to

Comparing Floating-Point Numbers q q To avoid roundoff errors, do not use == to compare floating-point numbers To compare floating-point numbers test whether they are close enough: |x - y| ≤ where is a small number such as 10 -14 final double EPSILON = 1 E-14; if (Math. abs(x - y) <= EPSILON) // x is approximately equal to y Chapter 5 Decisions 20

Comparing Strings q Do not use == for strings! if (input == "Y") //

Comparing Strings q Do not use == for strings! if (input == "Y") // WRONG!!! q Instead, use equals method if (input. equals("Y")) q For strings (objects) == tests identity, while equals tests equal content q Case insensitive test ("Y" or "y") if (input. equals. Ignore. Case("Y")) Chapter 5 Decisions 21

Comparing Strings q Do not ever use == for strings! q Can lead to

Comparing Strings q Do not ever use == for strings! q Can lead to subtle errors q For example String nickname = “Rob”; if(nickname == “Rob”) // test is true since one string object for any constant, but String name = “Robert”; String nickname = name. substring(0, 3); if(nickname == “Rob”) // test is false Chapter 5 Decisions 22

Comparing Strings q s. compare. To(t) < 0 means string s comes before string

Comparing Strings q s. compare. To(t) < 0 means string s comes before string t in the dictionary § For example, "car" comes before "cargo" q All uppercase letters come before lowercase: "Hello" comes before "car" Chapter 5 Decisions 23

Lexicographic Comparison Figure 3: Lexicographic Comparison Chapter 5 Decisions 24

Lexicographic Comparison Figure 3: Lexicographic Comparison Chapter 5 Decisions 24

Comparing Objects q == tests for identity q equals tests for identical content q

Comparing Objects q == tests for identity q equals tests for identical content q Rectangle box 1 = new Rectangle(5, 10, 20, 30); Rectangle box 2 = box 1; Rectangle box 3 = new Rectangle(5, 10, 20, 30); q box 1 != box 3 q box 1. equals(box 3) § Works only if equals defined for the class! q box 1 == box 2 Chapter 5 Decisions 25

Object Comparison Figure 4: Comparing Object References Chapter 5 Decisions 26

Object Comparison Figure 4: Comparing Object References Chapter 5 Decisions 26

Testing for null q null refers to no object String middle. Initial = null;

Testing for null q null refers to no object String middle. Initial = null; // Not set if (. . . ) middle. Initial = middle. Name. substring(0, 1); q Can be useful in tests if (middle. Initial == null) System. out. println(first. Name + " " + last. Name); else System. out. println(first. Name + " " + middle. Initial + ". " + last. Name); Chapter 5 Decisions 27

Testing for null q q Use ==, not equals, to test for null is

Testing for null q q Use ==, not equals, to test for null is not the same as the empty string "" Chapter 5 Decisions 28

Self Check 3. What is value of s. length() if s is a) the

Self Check 3. What is value of s. length() if s is a) the empty string, ""? b) the string " " (containing a single space)? c) null? Chapter 5 Decisions 29

Self-Check 4. Which of the following comparisons are syntactically incorrect? Which of them are

Self-Check 4. Which of the following comparisons are syntactically incorrect? Which of them are syntactically correct, but logically questionable? Chapter 5 Decisions String double a) b) c) d) e) f) g) h) a b x y = = "1"; "one"; 1; 3 * (1. 0 / 3); a == "1" a == null a. equals("") a == b a == x x == y x - y == null x. equals(y) 30

Answers 3. a) 0; b) 1; c) an exception (error) is “thrown” 4. Syntactically

Answers 3. a) 0; b) 1; c) an exception (error) is “thrown” 4. Syntactically incorrect: e, g, h Logically questionable: a, d, f Chapter 5 Decisions 31

Multiple Alternatives: Sequences of Comparisons q if (condition 1) statement 1; else if (condition

Multiple Alternatives: Sequences of Comparisons q if (condition 1) statement 1; else if (condition 2) statement 2; . . . else q Thestatement 4; first matching condition q The order matters! is executed if (richter >= 0) // always passes r = "Generally not felt by people"; else if (richter >= 3. 5) // not tested r = "Felt by many people"; . . . Chapter 5 Decisions 32

Multiple Alternatives: Sequences of Comparisons q Do not omit else if (richter >= 8.

Multiple Alternatives: Sequences of Comparisons q Do not omit else if (richter >= 8. 0) r = "Most structures fall"; if (richter >= 7. 0) // omitted else--ERROR r = "Many buildings destroyed"; q What happens here when richter is, say, 8. 5? Chapter 5 Decisions 33

File Earthquake. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11:

File Earthquake. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: /** A class that describes the effects of an earthquake. */ public class Earthquake { /** Constructs an Earthquake object. @param magnitude the magnitude on the Richter scale */ public Earthquake(double magnitude) { richter = magnitude; } /** Gets a description of the effect of the earthquake. @return the description of the effect Continued… */ Chapter 5 Decisions 34

File Earthquake. java 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29:

File Earthquake. java 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: public String get. Description() { String r; if (richter >= 8. 0) r = "Most structures fall"; else if (richter >= 7. 0) r = "Many buildings destroyed"; else if (richter >= 6. 0) r = "Many buildings considerably damaged, some collapse"; else if (richter >= 4. 5) r = "Damage to poorly constructed buildings"; else if (richter >= 3. 5) r = "Felt by many people, no destruction"; else if (richter >= 0) r = "Generally not felt by people"; else r = "Negative numbers are not valid"; return r; Continued… } Chapter 5 Decisions 35

File Earthquake. java 38: 39: private double richter; 40: } Chapter 5 Decisions 36

File Earthquake. java 38: 39: private double richter; 40: } Chapter 5 Decisions 36

File Earthquake. Tester. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10:

File Earthquake. Tester. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: import java. util. Scanner; /** A class to test the Earthquake class. */ public class Earthquake. Tester { public static void main(String[] args) { Scanner in = new Scanner(System. in); 13: 14: 15: 16: 17: } System. out. print("Enter a magnitude on the Richter scale: "); double magnitude = in. next. Double(); Earthquake = new Earthquake(magnitude); System. out. println(quake. get. Description()); } Chapter 5 Decisions 37

Multiple Alternatives: Nested Branches q q Branch inside another branch if (condition 1) {

Multiple Alternatives: Nested Branches q q Branch inside another branch if (condition 1) { if (condition 1 a) statement 1 a; else statement 1 b; } else statement 2; Braces { … } are especially important here! Chapter 5 Decisions 38

Tax Schedule If your filing status is single If your filing status is married

Tax Schedule If your filing status is single If your filing status is married Tax Bracket Percentage $0 … $21, 450 15% $0 … $35, 800 15% Amount over $21, 451, up to 28% $51, 900 Amount over $35, 800, up 28% to $86, 500 Amount over $51, 900 Amount over $86, 500 Chapter 5 Decisions 31% 39

Nested Branches q q q Compute taxes due, given filing status and income figure:

Nested Branches q q q Compute taxes due, given filing status and income figure: (1) branch on the filing status, (2) for each filing status, branch on income level The two-level decision process is reflected in two levels of if statements We say that the income test is nested inside the test for filing status Chapter 5 Decisions 40

Nested Branches Figure 5: Income Tax Computation Using 1992 Schedule Chapter 5 Decisions 41

Nested Branches Figure 5: Income Tax Computation Using 1992 Schedule Chapter 5 Decisions 41

File Tax. Return. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10:

File Tax. Return. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: /** A tax return of a taxpayer in 1992. */ public class Tax. Return { /** Constructs a Tax. Return object for a given income and marital status. @param an. Income the taxpayer income @param a. Status either SINGLE or MARRIED */ public Tax. Return(double an. Income, int a. Status) { income = an. Income; status = a. Status; } Continued… Chapter 5 Decisions 42

File Tax. Return. java 18: 19: 20: 21: 22: 23: 24: 25: 26: 27:

File Tax. Return. java 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: public double get. Tax() { double tax = 0; if (status == SINGLE) { if (income <= SINGLE_BRACKET 1) tax = RATE 1 * income; else if (income <= SINGLE_BRACKET 2) tax = RATE 1 * SINGLE_BRACKET 1 + RATE 2 * (income - SINGLE_BRACKET 1); else tax = RATE 1 * SINGLE_BRACKET 1 + RATE 2 * (SINGLE_BRACKET 2 – SINGLE_BRACKET 1) + RATE 3 * (income - SINGLE_BRACKET 2); } Continued… Chapter 5 Decisions 43

File Tax. Return. java 34: 35: 36: 37: 38: 39: 40: 41: 42: 43:

File Tax. Return. java 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: else { if (income <= MARRIED_BRACKET 1) tax = RATE 1 * income; else if (income <= MARRIED_BRACKET 2) tax = RATE 1 * MARRIED_BRACKET 1 + RATE 2 * (income - MARRIED_BRACKET 1); else tax = RATE 1 * MARRIED_BRACKET 1 + RATE 2 * (MARRIED_BRACKET 2 - MARRIED_BRACKET 1) + RATE 3 * (income - MARRIED_BRACKET 2); } return tax; } public static final int SINGLE = 1; public static final int MARRIED = 2; Continued… Chapter 5 Decisions 44

File Tax. Return. java 53: 54: 55: 56: 57: 58: 59: 60: 61: 62:

File Tax. Return. java 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: } private static final double RATE 1 = 0. 15; private static final double RATE 2 = 0. 28; private static final double RATE 3 = 0. 31; private static final double SINGLE_BRACKET 1 = 21450; private static final double SINGLE_BRACKET 2 = 51900; private static final double MARRIED_BRACKET 1 = 35800; private static final double MARRIED_BRACKET 2 = 86500; private double income; private int status; Chapter 5 Decisions 45

File Tax. Return. Tester. java 01: 02: 03: 04: 05: 06: 07: 08: 09:

File Tax. Return. Tester. java 01: 02: 03: 04: 05: 06: 07: 08: 09: 10: 11: 12: 13: 14: 15: 16: 17: 18: import java. util. Scanner; /** A class to test the Tax. Return class. */ public class Tax. Return. Tester { public static void main(String[] args) { Scanner in = new Scanner(System. in); System. out. print("Please enter your income: "); double income = in. next. Double(); System. out. print("Please enter S (single) or M (married): "); String input = in. next(); int status = 0; Chapter 5 Decisions 46

File Tax. Return. Tester. java 19: 20: 21: 22: 23: 24: 25: 26: 27:

File Tax. Return. Tester. java 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: } if (input. equals. Ignore. Case("S")) status = Tax. Return. SINGLE; else if (input. equals. Ignore. Case("M")) status = Tax. Return. MARRIED; else { System. out. println("Bad input. "); return; } Tax. Return a. Tax. Return = new Tax. Return(income, status); System. out. println("The tax is " + a. Tax. Return. get. Tax()); } Chapter 5 Decisions 47

File Tax. Return. Tester. java Output Please enter your income: 50000 Please enter S

File Tax. Return. Tester. java Output Please enter your income: 50000 Please enter S (single) or M (married): S The tax is 11211. 5 Chapter 5 Decisions 48

Self Check 5. The if/else statement for the earthquake strength first tested for higher

Self Check 5. The if/else statement for the earthquake strength first tested for higher values, then descended to lower values. Can you reverse that order? 6. Some people object to higher tax rates for higher incomes, claiming that you might end up with less money after taxes when you get a raise for working hard. What is the flaw in this argument? Chapter 5 Decisions 49

Answers 5. Yes, if you also reverse the comparisons: if (richter < 3. 5)

Answers 5. Yes, if you also reverse the comparisons: if (richter < 3. 5) r = "Generally not felt by people"; else if (richter < 4. 5) r = "Felt by many people, no destruction"; else if (richter < 6. 0) r = "Damage to poorly constructed buildings"; . . . Chapter 5 Decisions 50

Answers 6. The higher tax rate is only applied on the income in the

Answers 6. The higher tax rate is only applied on the income in the higher bracket. Suppose you are single and make $51, 800. Should you try to get a $200 raise? Absolutely–you get to keep 72% of the first $100 and 69% of the next $100 Chapter 5 Decisions 51

Using Boolean Expressions: The boolean Type q George Boole (1815 -1864) § Pioneer in

Using Boolean Expressions: The boolean Type q George Boole (1815 -1864) § Pioneer in the study of logic q Value of expression such as amount < 1000 § Either true or false q boolean date type § One of these 2 truth values: true or false Chapter 5 Decisions 52

Using Boolean Expressions: The boolean Type Chapter 5 Decisions 53

Using Boolean Expressions: The boolean Type Chapter 5 Decisions 53

Using Boolean Expressions: Predicate Method q A predicate method returns a boolean value public

Using Boolean Expressions: Predicate Method q A predicate method returns a boolean value public boolean is. Overdrawn() { return balance < 0; } q Useful in conditions such as if (harrys. Checking. is. Overdrawn()). . . Chapter 5 Decisions 54

Using Boolean Expressions: Predicate Method q Useful predicate methods in Character class is. Digit

Using Boolean Expressions: Predicate Method q Useful predicate methods in Character class is. Digit is. Letter is. Upper. Case is. Lower. Case q if (Character. is. Upper. Case(ch)). . . q Useful predicate methods in Scanner class has. Next. Int() and has. Next. Double() if (in. has. Next. Int()) n = in. next. Int(); Chapter 5 Decisions 55

Using Boolean Expressions: The Boolean Operators q && and q || or q !

Using Boolean Expressions: The Boolean Operators q && and q || or q ! not q if (0 < amount && amount < 1000). . . q if (input. equals("S") || input. equals("M")). . . Chapter 5 Decisions 56

&& and || Operators Figure 6: Flowcharts for && and || Combinations Chapter 5

&& and || Operators Figure 6: Flowcharts for && and || Combinations Chapter 5 Decisions 57

Truth Tables A True False B True False Any A&&B True False A True

Truth Tables A True False B True False Any A&&B True False A True False q A B A||B True False Any True False !A False True Java uses “short circuit evaluation Chapter 5 Decisions 58

Using Boolean Variables q Example: q Set to truth value: q Use in conditionals:

Using Boolean Variables q Example: q Set to truth value: q Use in conditionals: Chapter 5 Decisions private boolean married; married = input. equals("M"); if (married). . . else. . . if (!married). . . 59

Using Boolean Variables q Also called a flag q It is considered gauche to

Using Boolean Variables q Also called a flag q It is considered gauche to write a test such as if (married == true). . . // Not cool q Just use the simpler expression if (married). . . Chapter 5 Decisions 60

Self Check 7. When does the statement System. out. println (x > 0 ||

Self Check 7. When does the statement System. out. println (x > 0 || x < 0); print false? 8. Rewrite the following expression, avoiding the comparison with false if (Character. is. Digit(ch) == false). . . Chapter 5 Decisions 61

Answers 7. 8. When x is zero if (!Character. is. Digit(ch)). . . Chapter

Answers 7. 8. When x is zero if (!Character. is. Digit(ch)). . . Chapter 5 Decisions 62

De Morgan’s Laws q !(A && B) is the same as (!A)||(!B) q !(A

De Morgan’s Laws q !(A && B) is the same as (!A)||(!B) q !(A || B) is the same as (!A)&&(!B) Chapter 5 Decisions 63

switch Statement q The switch must be an int (see pp. 205 -6) int

switch Statement q The switch must be an int (see pp. 205 -6) int digit; . . . switch (digit) { case 1: System. out. println(“one”); break; case 2: System. out. println(“two”); break; default: System. out. println(“try again”); break; } q A shortcut for a sequence of if/else if int digit; . . . if (digit == 1) System. out. println(“one”); else if (digit == 2) System. out. println(“two”); else System. out. println(“try again”); Chapter 5 Decisions 64