• No results found

Chapter 5 Decisions

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 5 Decisions"

Copied!
51
0
0

Loading.... (view fulltext now)

Full text

(1)

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

(3)

if Statement

if (amount <= balance)

balance = balance - amount;

(4)

if/else Statement

if (amount <= balance)

balance = balance - amount;

else

balance = balance - OVERDRAFT_PENA LTY;

(5)

Block Statement

if (amount <= balance) {

double newBalance = balance - amount;

balance = newBalance;

}

(6)

Syntax 5.1. The if Statement

if(condition) statement

if (condition) statement else

statement

Example:

if (amount <= balance)

balance = balance - amount;

(7)

if (amount <= balance)

balance = balance - amount;

else

balance = balance - OVERDRAFT_PENALTY;

– Purpose:

To execute a statement when a condition is true or false

(8)

Syntax 5.2. Block Statement

{

statement . . .

}

Example:

{

double newBalance = balance - amount;

balance = newBalance;

}

Purpose:

To group several statements together to form a single

(9)

Statement Types

 Simple statement

balance = balance - amount;

 Compound statement

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

Also while, for, etc. (see chapter 6)

 Block statement {

double newBalance = balance - amount;

balance = newBalance;

(10)

Relational Operators

Java Math Notation Description

> > Greater than

>= &ge;

Greater than or equal

< < Less than

<= &le;

Less than or equal

== = Equal

(11)

Equality Testing vs. Assignment

 The = = operator tests for equality:

if (x = = 0) . . // if x equals zero

 The = operator assigns a value to a variable:

x = 0; // assign 0 to x

 Don't confuse them.

 Java = = is the same as mathematical =

(12)

Comparing Floating-Point Numbers

 Consider this 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 is not 0 but " + d);

(13)

 It prints:

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

 Don't use == to compare floating-point numbers

(14)

Comparing Floating-Point Numbers

 Two numbers are close to another if

|x - y| <= ε

 ε is a small number such as 10-14

 Not good enough if x, y very large or very small.

Then use

|x - y| / max(|x|, |y|) <= ε

 But if one of the numbers is zero, don't divide by max(|x |, |y|)

(15)

String Comparison

 Don't use = = for strings!

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

 Use equals method:

if (input.equals("Y"))

 = = tests identity, equals tests equal contents

 Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y"))

(16)

Lexicographic Comparison

 s.compareTo(t) < 0 means:

s comes before t in the dictionary

 "car"comes before "cargo"

"cargo" comes before "cathode"

 All uppercase letters come before lowercase:

"Hello" comes before "car"

(17)

Lexicographic Comparison

(18)

Object Comparison

 = = tests for identity, equals for identical content

 Rectangle cerealBox = new Rectangle(5, 10, 20, 30);

Rectangle oatmealBox = new Rectangle(5, 10, 20, 30);

Rectangle r = cerealBox;

 cerealBox != oatmealBox,

but cerealBox.equals(oatmealBox)

 cerealBox == r

 Caveat: equals must be defined for the class (see

(19)

Object Comparison

(20)

The null Reference

null reference refers to no object at all

Can be used in tests:

if (account == null) . . .

Use ==, not equals, to test for null

showInputDialog returns null if the user hit the cancel button:

String input =

JOptionPane.showInputDialog("...");

if (input != null) { ... }

(21)

Multiple Alternatives

• if (condition1) statement1;

else if (condition2) statement2;

else if (condition3) statement3;

else

statement4;

• The first matching condition is executed.

• Order matters.

(22)

File Earthquake.java

1 /**

2 A class that describes the effects of an earthquake.

3 */

4 public class Earthquake 5 {

6 /**

7 Constructs an Earthquake object.

8 @param magnitude the magnitude on the Richter scale

(23)

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 effect 18 */

19 public String getDescription() 20 {

(24)

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)

(25)

32 else if (richter >= 0)

33 r = "Generally not felt by people";

34 else

35 r = "Negative numbers are not valid";

36 return r;

37 } 38

39 private double richter;

40 }

(26)

File EarthquakeTest.java

1 import javax.swing.JOptionPane;

2

3 /**

4 A class to test the Earthquake class.

5 */

6 public class EarthquakeTest 7 {

(27)

8 public static void main(String[] args) 9 {

10 String input = JOptionPane.showInputDialog(

11 "Enter a magnitude on the Richter scale:");

12 double magnitude = Double.parseDouble(input);

13 Earthquake quake = new Earthquake(magnitude);

14 System.out.println(quake.getDescription()) 15 System.exit(0);

16 }

(28)

Multiple Alternatives

 Order matters:

if (richter >= 0) // always passes r = "Generally not felt by people";

else if (richter >= 3.5) // not tested

r = "Felt by many people, no destruction";

. . .

 Don't omit else if (richter >= 8.0)

r = "Most structures fall";

if (richter >= 7.0) // omitted else--ERROR

(29)

Nested Branches

• Branch inside another branch if (condition1)

{

if (condition1a) statement1a;

else

statement1b;

} else

(30)

Tax Return

• If your filing status is Single

If the taxable income is over

But not over

The tax is Of the

amount over

$0 $21,450 15% $0

$21,450 $51,900 $3,217.50 + 28%

$21,450

$51,900 $11,743.50

+ 31%

$51,900

(31)

• If your filing status is Married

If the taxable income is over

But not over

The tax is Of the amount over

$0 $35,800 15% $0

$35,800 $86,500 $5,370.00 + 28%

$35,800

$86,500 $19,566.0

0 + 31%

$86,500

(32)

Tax Return

(33)

File TaxReturn.java

1 /**

2 A tax return of a taxpayer in 1992.

3 */

4 class TaxReturn 5 {

6 /**

7 Constructs a TaxReturn object for a given income and 8 marital status.

9 @param anIncome the taxpayer income

10 @param aStatus either SINGLE or MARRIED 11 */

(34)

12 public TaxReturn(double anIncome, int aStatus) 13 {

14 income = anIncome;

15 status = aStatus;

16 } 17

18 public double getTax() 19 {

20 double tax = 0;

21

(35)

22 if (status == SINGLE) 23 {

24 if (income <= SINGLE_CUTOFF1) 25 tax = RATE1 * income;

26 else if (income <= SINGLE_CUTOFF2) 27 tax = SINGLE_BASE2

28 + RATE2 * (income - SINGLE_CUTOFF1);

29 else

30 tax = SINGLE_BASE3

31 + RATE3 * (income - SINGLE_CUTOFF2);

(36)

33 else 34 {

35 if (income <= MARRIED_CUTOFF1) 36 tax = RATE1 * income;

37 else if (income <= MARRIED_CUTOFF2) 38 tax = MARRIED_BASE2

39 + RATE2 * (income - MARRIED_CUTOFF1);

40 else

41 tax = MARRIED_BASE3

42 + RATE3 * (income - MARRIED_CUTOFF2);

(37)

44

45 return tax;

46 } 47

48 public static final int SINGLE = 1;

49 public static final int MARRIED = 2;

50

51 private static final double RATE1 = 0.15;

52 private static final double RATE2 = 0.28;

(38)

55 private static final double SINGLE_CUTOFF1 = 21450;

56 private static final double SINGLE_CUTOFF2 = 51900;

57

58 private static final double SINGLE_BASE2 = 3217.50;

59 private static final double SINGLE_BASE3 = 11743.50;

60 private static final double MARRIED_CUTOFF1 = 35800;

61 private static final double MARRIED_CUTOFF2 = 86500;

(39)

62

63 private static final double MARRIED_BASE2 = 5370;

64 private static final double MARRIED_BASE3 = 19566;

65

66 private double income;

67 private int status;

68 }

(40)

File TaxReturnTest.java

1 import javax.swing.JOptionPane;

2

3 /**

4 A class to test the TaxReturn class.

5 */

6 public class TaxReturnTest 7 {

8 public static void main(String[] args)

(41)

10 String input = JOptionPane.showInputDialog(

11 "Please enter your income:");

12 double income = Double.parseDouble(input);

13

14 input = JOptionPane.showInputDialog(

15 "Please enter S (single) or M (married)");

16 int status = 0;

17

18 if (input.equalsIgnoreCase("S")) 19 status = TaxReturn.SINGLE;

(42)

22 else 23 {

24 System.out.println("Bad input.");

25 System.exit(0);

26 } 27

28 TaxReturn aTaxReturn = new TaxReturn(income, status);

29

30 System.out.println("The tax is "

31 + aTaxReturn.getTax());

(43)

32

33 System.exit(0);

34 } 35 }

(44)

The boolean Type

 George Boole (1815-1864): pioneer in the study of logic

 value of expression amount < 1000 is true or false.

 boolean type: one of these 2 truth values

(45)

Predicate Method

 return type boolean

 Example:

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

 Use in conditions

if (harrysChecking.isOverdrawn()) ...

 Useful predicate methods in Character class:

isDigit isLetter

isUpperCase isLowerCase

(46)

Boolean Operators

 && and

 || or

 ! not

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

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

(47)

&& and || Operators

(48)

Truth Tables

A B A && B

true true true

true false false

false Any false

A B A || B

true Any true

false true true

(49)

A ! A

true false

false true

(50)

De Morgan's Law

 Negating a complex condition can be confusing:

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

 De Morgan's law states that

!(A && B) is the same as !A || !B

!(A || B) is the same as !A && !B

 Note that the && and || flip when moving the ! inwards

 (!(0 < amount && amount < 1000)) is

!(0 < amount) || !(amount < 1000) , that is 0 >= amount || amount >= 1000

 Note that the opposite of < is >=

(51)

Boolean Variables

 private boolean married;

 Set to truth value:

married = input.equals("M");

 Use in conditions:

if (married) ... else ...

if (!married) ...

 Also called flag

 Don't test Boolean variables against truth values--sign of cluelessness:

if (married == true) // DON'T if (married == false) // DON'T

References

Related documents

The Professional Bail Bondsman Licensing Board utilizes this appropriation to cover operating expenses and to administer and enforce the provisions of the law relating to

Regarding empirical hypothesis, table 6 shows that the coefficient of the variable credit quality (which proxies for private information, and defines the

Quarter Page Vertical 124mm x 92mm Quarter Page Horizontal 59mm x 188mm Eighth Page Horizontal 59mm x 92mm Eighth Page Vertical 124mm x 44mm One Sixteenth 59mm x 44mm Small

*We who have ticked the Gift Aid column above want Cool Earth to reclaim the tax back on any donations we have made over the last six years and all future donations until we notify

This makes them more likely to enjoy faster accumulation of inventive experience in their technological fields compared to vertically-integrated small firms – which instead

“The hypertext is less an edition than an archive, and it is one thing to have such (hyper)textual richness available and quite another to read it.”50 Kastan’s view

In order to avoid contamination of our results from banking systems that do not seem to operate in ‘equilibrium’, when we pool all the banks in our sample, we are also going to

Living without having their basic needs met may cause homeless single mothers and their children stress that may compromise their mental and physical health.. Poverty-related