chapter 5 decisions

64
Chapter 5 Decisions 1 Chapter 5 Decisions

Upload: jenski

Post on 10-Feb-2016

54 views

Category:

Documents


0 download

DESCRIPTION

Chapter 5 Decisions. Chapter Goals. To be able to implement decisions using if statements To understand how to group statements into blocks To learn how to compare integers, floating-point numbers, strings and objects To recognize the correct ordering of decisions in multiple branches - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 5 Decisions

Chapter 5 Decisions 1

Chapter 5

Decisions

Page 2: Chapter 5 Decisions

Chapter 5 Decisions 2

Chapter Goals To be able to implement decisions using if

statements To understand how to group statements into blocks 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

Page 3: Chapter 5 Decisions

Chapter 5 Decisions 3

The if Statement The if statement lets a program carry

out different actions depending on a condition if (amount <= balance) balance = balance - amount;

Page 4: Chapter 5 Decisions

Chapter 5 Decisions 4

The if Statement

Figure 1:Flowchart for an if statement

Page 5: Chapter 5 Decisions

Chapter 5 Decisions 5

The if/else Statement

if (amount <= balance) balance = balance - amount;else balance = balance - OVERDRAFT_PENALTY;

Why doesn’t this work?

Use if/else to choose between alternatives

if (amount <= balance) balance = balance - amount;if (amount > balance) balance = balance - OVERDRAFT_PENALTY;

Page 6: Chapter 5 Decisions

Chapter 5 Decisions 6

The if/else Statement

Figure 2:Flowchart for an if/else statement

Page 7: Chapter 5 Decisions

Chapter 5 Decisions 7

Statement Types Simple statement

Compound statement

Other examples in Java: while, for, etc. (loop statements, discussed in Chapter 7)

balance = balance - amount;

if (balance >= amount) balance = balance - amount;

Page 8: Chapter 5 Decisions

Chapter 5 Decisions 8

Statement Types Block statement: enclose multiple

simple statements in { … }

For example

{    double newBalance = balance - amount;    balance = newBalance;}

if (amount <= balance){    double newBalance = balance - amount;    balance = newBalance;}

Page 9: Chapter 5 Decisions

Chapter 5 Decisions 9

Syntax 6.1: The if Statement if(condition)   statement

if (condition)   statement1else   statement2Example: if (amount <= balance) balance = balance - amount;

if (amount <= balance) balance = balance - amount; else balance = balance - OVERDRAFT_PENALTY;Purpose:To execute a statement when a condition is true or false

Page 10: Chapter 5 Decisions

Chapter 5 Decisions 10

Syntax 6.2: Block Statement {   statement1

   statement2

   . . . }

Example: { double newBalance = balance - amount; balance = newBalance; }

Purpose:To group several statements together to form a single statement

Page 11: Chapter 5 Decisions

Chapter 5 Decisions 11

Brace Layout Compiler doesn’t care how braces align

For human readability, make braces line up

Good idea to use braces for all if statements

if (amount <= balance){    double newBalance = balance - amount;    balance = newBalance;}

if (amount <= balance){    double newBalance = balance - amount;    balance = newBalance;}

Page 12: Chapter 5 Decisions

Chapter 5 Decisions 12

Brace Layout 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

For example, this is good…

But this will lose points…

if (amount <= balance){    double newBalance = balance - amount;}

if (amount <= balance)    double newBalance = balance - amount;

Page 13: Chapter 5 Decisions

Chapter 5 Decisions 13

Brace Layout You must also be able to read code when

braces are not used with if statements Since braces not always required by Java

syntax In slides and book, braces are often

omitted But always use braces in if statements for

code you write in this class Got it?

Page 14: Chapter 5 Decisions

Chapter 5 Decisions 14

Self-Check1. Why did we use the condition

amount <= balance and not amount < balance in if/else example?

2. What is wrong with the statement

and how can you fix it? Is this a logic or syntax error?

if (amount <= balance)newBalance = balance - amount; balance = newBalance;

Page 15: Chapter 5 Decisions

Chapter 5 Decisions 15

Answers1. 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.

Page 16: Chapter 5 Decisions

Chapter 5 Decisions 16

Selection Operator A shorthand way to do if/else

value1 result of “if” value2 result of “else”

For example

can be used in place of if/else construct

condition ? value1 : value2

y = x >= 0 ? x : -x;

if(x >= 0) y = x;else y = -x;

Page 17: Chapter 5 Decisions

Chapter 5 Decisions 17

Comparing Values: Relational Operators

Relational operators compare values

The == operator denotes equality testing

Java Math Notation Description> > Greater than>= ≥ Greater than or equal< < Less than<= ≤ Less than or equal== = Equal!= ≠ Not equal

a = 5; // Assign 5 to a if (a == 5) . . . // Test whether a equals 5

Page 18: Chapter 5 Decisions

Chapter 5 Decisions 18

Comparing Values: Relational Operators

“==“ often leads to errors For example

This is probably what was intendeda = 5; // Assign 5 to a if (a = 5) . . . // what happens here?

a = 5; // Assign 5 to a if (a == 5) . . . // Test whether a == 5

Page 19: Chapter 5 Decisions

Chapter 5 Decisions 19

Comparing Floating-Point Numbers

Consider the code

This code prints 

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

sqrt(2)squared minus 2 is not 0 but 4.440892098500626E-16

Page 20: Chapter 5 Decisions

Chapter 5 Decisions 20

Comparing Floating-Point Numbers

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 = 1E-14;if (Math.abs(x - y) <= EPSILON) // x is approximately equal to y

Page 21: Chapter 5 Decisions

Chapter 5 Decisions 21

Comparing Strings Do not use == for strings!

Instead, use equals method

For strings (objects) == tests identity, while equals tests equal content

Case insensitive test ("Y" or "y")

if (input == "Y") // WRONG!!!

if (input.equals("Y"))

if (input.equalsIgnoreCase("Y"))

Page 22: Chapter 5 Decisions

Chapter 5 Decisions 22

Comparing Strings Do not ever use == for strings! Can lead to subtle errors For example

since one string object for any constant, but

String nickname = “Rob”;if(nickname == “Rob”) // test is true

String name = “Robert”;String nickname = name.substring(0,3);if(nickname == “Rob”) // test is false

Page 23: Chapter 5 Decisions

Chapter 5 Decisions 23

Comparing Strings s.compareTo(t) < 0 means string

s comes before string t in the dictionary For example, "car" comes before "cargo"

All uppercase letters come before lowercase: "Hello" comes before "car"

Page 24: Chapter 5 Decisions

Chapter 5 Decisions 24

Lexicographic Comparison

Figure 3: Lexicographic Comparison

Page 25: Chapter 5 Decisions

Chapter 5 Decisions 25

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

box1 != box3 box1.equals(box3)

Works only if equals defined for the class! box1 == box2

Rectangle box1 = new Rectangle(5, 10, 20, 30);Rectangle box2 = box1;Rectangle box3 = new Rectangle(5, 10, 20, 30);

Page 26: Chapter 5 Decisions

Chapter 5 Decisions 26

Object Comparison

Figure 4:Comparing Object References

Page 27: Chapter 5 Decisions

Chapter 5 Decisions 27

Testing for null null refers to no object

Can be useful in tests

String middleInitial = null; // Not setif ( . . . ) middleInitial = middleName.substring(0, 1);

if (middleInitial == null) System.out.println(firstName + " " + lastName);else System.out.println(firstName + " " + middleInitial + ". "

+ lastName);

Page 28: Chapter 5 Decisions

Chapter 5 Decisions 28

Testing for null Use ==, not equals, to test for null null is not the same as the empty string ""

Page 29: Chapter 5 Decisions

Chapter 5 Decisions 29

Self Check3. What is value of s.length() if s is

a) the empty string, ""? b) the string " " (containing a single

space)? c) null?

Page 30: Chapter 5 Decisions

Chapter 5 Decisions 30

Self-CheckString a = "1";String b = "one";double x = 1;double y = 3 * (1.0 / 3);

a) a == "1" b) a == null c) a.equals("") d) a == b e) a == x f) x == y g) x - y == null h) x.equals(y)

4. Which of the following comparisons are syntactically incorrect? Which of them are syntactically correct, but logically questionable?

Page 31: Chapter 5 Decisions

Chapter 5 Decisions 31

Answers3. a) 0; b) 1; c) an exception (error) is

“thrown” 4. Syntactically incorrect: e, g, h

Logically questionable: a, d, f

Page 32: Chapter 5 Decisions

Chapter 5 Decisions 32

Multiple Alternatives: Sequences of Comparisons

The first matching condition is executed The order

matters!

if (condition1)   statement1;else if (condition2)   statement2;. . .else   statement4;

if (richter >= 0) // always passes   r = "Generally not felt by people";else if (richter >= 3.5) // not tested   r = "Felt by many people";. . .

Page 33: Chapter 5 Decisions

Chapter 5 Decisions 33

Multiple Alternatives: Sequences of Comparisons

Do not omit else

What happens here when richter is, say, 8.5?

if (richter >= 8.0)   r = "Most structures fall";if (richter >= 7.0) // omitted else--ERROR   r = "Many buildings destroyed";

Page 34: Chapter 5 Decisions

Chapter 5 Decisions 34

File Earthquake.java01: /**02: A class that describes the effects of an earthquake.03: */04: public class Earthquake05: { 06: /**07: Constructs an Earthquake object.08: @param magnitude the magnitude on the Richter scale09: */10: public Earthquake(double magnitude)11: { 12: richter = magnitude;13: }14: 15: /**16: Gets a description of the effect of the earthquake.17: @return the description of the effect18: */ Continued…

Page 35: Chapter 5 Decisions

Chapter 5 Decisions 35

File Earthquake.java19: public String getDescription()20: {21: String r;22: if (richter >= 8.0)23: r = "Most structures fall";24: else if (richter >= 7.0)25: r = "Many buildings destroyed";26: else if (richter >= 6.0)27: r = "Many buildings considerably damaged, some collapse";28: else if (richter >= 4.5)29: r = "Damage to poorly constructed buildings";30: else if (richter >= 3.5)31: r = "Felt by many people, no destruction";32: else if (richter >= 0)33: r = "Generally not felt by people";34: else35: r = "Negative numbers are not valid";36: return r;37: } Continued…

Page 36: Chapter 5 Decisions

Chapter 5 Decisions 36

File Earthquake.java38: 39: private double richter; 40: }

Page 37: Chapter 5 Decisions

Chapter 5 Decisions 37

File EarthquakeTester.java01: import java.util.Scanner;02: 03: /**04: A class to test the Earthquake class.05: */06: public class EarthquakeTester07: { 08: public static void main(String[] args)09: { 10: Scanner in = new Scanner(System.in);11: 12: System.out.print("Enter a magnitude on the Richter scale: ");13: double magnitude = in.nextDouble();14: Earthquake quake = new Earthquake(magnitude);15: System.out.println(quake.getDescription());16: }17: }

Page 38: Chapter 5 Decisions

Chapter 5 Decisions 38

Multiple Alternatives: Nested Branches

Branch inside another branch

Braces { … } are especially important here!

if (condition1){ if (condition1a) statement1a; else statement1b;}else statement2;

Page 39: Chapter 5 Decisions

Chapter 5 Decisions 39

Tax Schedule

If your filing status is single If your filing status is marriedTax Bracket Percenta

geTax Bracket Percenta

ge$0 … $21,450 15% $0 … $35,800 15%Amount over $21,451, up to $51,900

28% Amount over $35,800, up to $86,500

28%

Amount over $51,900 31% Amount over $86,500 31%

Page 40: Chapter 5 Decisions

Chapter 5 Decisions 40

Nested Branches 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

Page 41: Chapter 5 Decisions

Chapter 5 Decisions 41

Nested Branches

Figure 5:Income Tax Computation Using 1992 Schedule

Page 42: Chapter 5 Decisions

Chapter 5 Decisions 42

File TaxReturn.java01: /**02: A tax return of a taxpayer in 1992.03: */04: public class TaxReturn05: { 06: /**07: Constructs a TaxReturn object for a given income and 08: marital status.09: @param anIncome the taxpayer income10: @param aStatus either SINGLE or MARRIED11: */ 12: public TaxReturn(double anIncome, int aStatus)13: { 14: income = anIncome;15: status = aStatus;16: }17: Continued…

Page 43: Chapter 5 Decisions

Chapter 5 Decisions 43

File TaxReturn.java18: public double getTax()19: { 20: double tax = 0;21: 22: if (status == SINGLE)23: { 24: if (income <= SINGLE_BRACKET1)25: tax = RATE1 * income;26: else if (income <= SINGLE_BRACKET2)27: tax = RATE1 * SINGLE_BRACKET128: + RATE2 * (income - SINGLE_BRACKET1);29: else30: tax = RATE1 * SINGLE_BRACKET131: + RATE2 * (SINGLE_BRACKET2 – SINGLE_BRACKET1)32: + RATE3 * (income - SINGLE_BRACKET2);33: } Continued…

Page 44: Chapter 5 Decisions

Chapter 5 Decisions 44

File TaxReturn.java34: else35: { 36: if (income <= MARRIED_BRACKET1)37: tax = RATE1 * income;38: else if (income <= MARRIED_BRACKET2)39: tax = RATE1 * MARRIED_BRACKET140: + RATE2 * (income - MARRIED_BRACKET1);41: else42: tax = RATE1 * MARRIED_BRACKET143: + RATE2 * (MARRIED_BRACKET2 - MARRIED_BRACKET1)44: + RATE3 * (income - MARRIED_BRACKET2);45: }46: 47: return tax;48: }49: 50: public static final int SINGLE = 1;51: public static final int MARRIED = 2;52: Continued…

Page 45: Chapter 5 Decisions

Chapter 5 Decisions 45

File TaxReturn.java53: private static final double RATE1 = 0.15;54: private static final double RATE2 = 0.28;55: private static final double RATE3 = 0.31;56: 57: private static final double SINGLE_BRACKET1 = 21450;58: private static final double SINGLE_BRACKET2 = 51900;59: 60: private static final double MARRIED_BRACKET1 = 35800;61: private static final double MARRIED_BRACKET2 = 86500;62: 63: private double income;64: private int status;65: }

Page 46: Chapter 5 Decisions

Chapter 5 Decisions 46

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

Page 47: Chapter 5 Decisions

Chapter 5 Decisions 47

File TaxReturnTester.java19: if (input.equalsIgnoreCase("S")) 20: status = TaxReturn.SINGLE;21: else if (input.equalsIgnoreCase("M")) 22: status = TaxReturn.MARRIED;23: else 24: {25: System.out.println("Bad input.");26: return;27: } 28: 29: TaxReturn aTaxReturn = new TaxReturn(income, status);30: 31: System.out.println("The tax is "32: + aTaxReturn.getTax());33: }34: }

Page 48: Chapter 5 Decisions

Chapter 5 Decisions 48

File TaxReturnTester.java

Please enter your income: 50000 Please enter S (single) or M (married): S The tax is 11211.5

Output

Page 49: Chapter 5 Decisions

Chapter 5 Decisions 49

Self Check5. 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?

Page 50: Chapter 5 Decisions

Chapter 5 Decisions 50

Answers5. 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";. . .

Page 51: Chapter 5 Decisions

Chapter 5 Decisions 51

Answers6. 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

Page 52: Chapter 5 Decisions

Chapter 5 Decisions 52

Using Boolean Expressions: The boolean Type

George Boole (1815-1864) Pioneer in the study of logic

Value of expression such as amount < 1000 Either true or false

boolean date type One of these 2 truth values: true or false

Page 53: Chapter 5 Decisions

Chapter 5 Decisions 53

Using Boolean Expressions: The boolean Type

Page 54: Chapter 5 Decisions

Chapter 5 Decisions 54

Using Boolean Expressions: Predicate Method

A predicate method returns a boolean value

Useful in conditions such as

public boolean isOverdrawn(){   return balance < 0; }

if (harrysChecking.isOverdrawn()) . . .

Page 55: Chapter 5 Decisions

Chapter 5 Decisions 55

Using Boolean Expressions: Predicate Method

Useful predicate methods in Character class

Useful predicate methods in Scanner class hasNextInt() and hasNextDouble()

isDigitisLetterisUpperCaseisLowerCase

if (Character.isUpperCase(ch)) . . .

if (in.hasNextInt()) n = in.nextInt();

Page 56: Chapter 5 Decisions

Chapter 5 Decisions 56

Using Boolean Expressions: The Boolean Operators

&&  and ||  or !   not

if (0 < amount && amount < 1000) . . .

if (input.equals("S") || input.equals("M")) . . .

Page 57: Chapter 5 Decisions

Chapter 5 Decisions 57

&& and || Operators

Figure 6:Flowcharts for && and || Combinations

Page 58: Chapter 5 Decisions

Chapter 5 Decisions 58

Truth TablesA B A||BTrue Any TrueFalse True TrueFalse False False

A B A&&BTrue True TrueTrue False FalseFalse Any False

A !ATrue FalseFalse True

Java uses “short circuit evaluation

Page 59: Chapter 5 Decisions

Chapter 5 Decisions 59

Using Boolean Variables Example:

Set to truth value:

Use in conditionals:

married = input.equals("M");

private boolean married;

if (married) . . . else . . .if (!married) . . .

Page 60: Chapter 5 Decisions

Chapter 5 Decisions 60

Using Boolean Variables Also called a flag It is considered gauche to write a test such

as

Just use the simpler expression

if (married == true) . . . // Not cool

if (married) . . .

Page 61: Chapter 5 Decisions

Chapter 5 Decisions 61

Self Check7. When does the statement

print false? 8. Rewrite the following expression,

avoiding the comparison with false

System.out.println (x > 0 || x < 0);

if (Character.isDigit(ch) == false) . . .

Page 62: Chapter 5 Decisions

Chapter 5 Decisions 62

Answers7. When x is zero 8. if (!Character.isDigit(ch)) . . .

Page 63: Chapter 5 Decisions

Chapter 5 Decisions 63

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

Page 64: Chapter 5 Decisions

Chapter 5 Decisions 64

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

A shortcut for a sequence of if/else if

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

int digit;. . .if (digit == 1) System.out.println(“one”);else if (digit == 2) System.out.println(“two”);else System.out.println(“try again”);