+ All Categories
Home > Documents > Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to...

Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to...

Date post: 19-Dec-2015
Category:
View: 225 times
Download: 4 times
Share this document with a friend
23
Chapter 5 Chapter 5 Decisions Decisions Goals Goals To be able To be able to implement to implement decisions using if statements decisions using if statements To understand how To understand how to group to group statements into blocks statements into blocks To learn how To learn how to compare to compare integers, floating-point integers, floating-point numbers, strings, and objects numbers, strings, and objects To recognize the To recognize the correct correct ordering of decisions in ordering of decisions in multiple branches multiple branches To To program conditions using program conditions using Boolean operators and Boolean operators and
Transcript
Page 1: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Chapter 5Chapter 5DecisionsDecisions

Goals Goals To be able To be able to implement decisions to implement decisions

using if statements using if statements To understand how To understand how to group to group

statements into blocks statements into blocks To learn how To learn how to compare integers, to compare integers,

floating-point numbers, strings, floating-point numbers, strings, and objects and objects

To recognize the To recognize the correct ordering correct ordering of decisions in multiple branches of decisions in multiple branches

To To program conditions using program conditions using Boolean operators and variablesBoolean operators and variables

Page 2: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

if if StatementStatement

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

if/else if/else StatementStatement

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

elseelse balance = balance - balance = balance - OVERDRAFT_PENALTY;OVERDRAFT_PENALTY;

FlowchartFlowchart

Page 3: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Syntax 5.1. The if Syntax 5.1. The if StatementStatement Syntax:Syntax:

Format 1:Format 1:

if (if (conditioncondition))statementstatement

Format 2:Format 2:

if (if (conditioncondition))statement1statement1

elseelsestatement2statement2

Example:Example: Format 1:Format 1:

if (amount <= balance)if (amount <= balance) balance = balance - balance = balance - amount;amount; Format 2:Format 2:

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

elseelse balance = balance - balance = balance - OVERDRAFT_PENALTY;OVERDRAFT_PENALTY; Purpose:Purpose:

To execute a statement when a condition is true or falseTo execute a statement when a condition is true or false

Page 4: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Syntax 5.2. Block Syntax 5.2. Block StatementStatement Syntax: Syntax:

{{statementstatement. . .. . .

}}

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

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

Page 5: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Statement TypesStatement Types Simple statementSimple statement

balance = balance - amount;balance = balance - amount; Compound statementCompound statement

if (balance >= amount) if (balance >= amount)

balance = balance - amount;balance = balance - amount; Also while, for, etc. (see chapter 6)Also while, for, etc. (see chapter 6)

Block statementBlock statement{{

double newBalance = balance - double newBalance = balance - amount;amount;

balance = newBalance;balance = newBalance;}}

Page 6: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Relational OperatorsRelational OperatorsJava Math Notation Description> > Greater than

>= &ge;Greater than or equal

< < Less than

<= &le;Less than or equal

== = EqualEquality Testing vs. Equality Testing vs.

AssignmentAssignment The == operator tests for The == operator tests for

equality:equality:if (x == 0) . . // if x equals zeroif (x == 0) . . // if x equals zero

The = operator assigns The = operator assigns a value to a variable:a value to a variable:x = 0; // assign 0 to x x = 0; // assign 0 to x

Java == is the same as mathematical =Java == is the same as mathematical =

Page 7: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Comparing Floating-Point Comparing Floating-Point NumbersNumbers Consider the code:Consider the code:

double r = Math.sqrt(2); double r = Math.sqrt(2); double d = r * r -2; double d = r * r -2; if (d == 0) if (d == 0) System.out.println( System.out.println( "sqrt(2)squared minus "sqrt(2)squared minus

2 is 0"); 2 is 0"); else else System.out.println( System.out.println( "sqrt(2)squared minus "sqrt(2)squared minus

2 is not 0 but " + 2 is not 0 but " + d);d);

It prints:It prints:sqrt(2)squared minus 2 is sqrt(2)squared minus 2 is not 0 but not 0 but 4.440892098500626E-164.440892098500626E-16

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

Two numbers are close to Two numbers are close to one another if one another if ||xx - - yy| <= ε| <= ε

ε is a small number such ε is a small number such as 10as 10-14-14

Not good enough if Not good enough if xx, , yy very large or very small. very large or very small. Then useThen use||xx - - yy| / max(|| / max(|xx|, ||, |yy|) <= ε|) <= ε

But if one of the numbers But if one of the numbers is zero, don't divide by is zero, don't divide by max(|max(|xx |, | |, |yy|) |)

Page 8: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

String ComparisonString Comparison Don't use == for stringsDon't use == for strings!!

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

Use Use equalsequals method method::if (input.equals("Y"))if (input.equals("Y"))

== tests identity, == tests identity, equalsequals tests equal contentstests equal contents

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

Lexicographic ComparisonLexicographic Comparison s.compareTo(t) < 0 s.compareTo(t) < 0

meansmeans:: s comes before t in the s comes before t in the dictionarydictionary

"car"comes before "car"comes before "cargo" "cargo" "cargo" comes before "cargo" comes before "cathode""cathode"

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

Page 9: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Object ComparisonObject Comparison ==== tests for identitytests for identity, , equalsequals

for identical content for identical content Rectangle cerealBox = new Rectangle cerealBox = new

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

cerealBox != oatmealBox, cerealBox != oatmealBox, but but cerealBox.equals(oatmealBocerealBox.equals(oatmealBox) x)

cerealBox == r and cerealBox == r and cerealBox.equals(r)cerealBox.equals(r)

Caveat: equals must be Caveat: equals must be defined for the class (see defined for the class (see chapter 11)chapter 11)

Page 10: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

The null The null ReferenceReference null reference refers null reference refers

to no object at all to no object at all Can be used in tests:Can be used in tests:

if (account == if (account == null) . . . null) . . .

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

showInputDialog showInputDialog returns null if the user returns null if the user hit the cancel button:hit the cancel button:String input = String input = JOptionPane.showInpuJOptionPane.showInputDialog("...");tDialog("...");if (input != null) { ... } if (input != null) { ... }

null is not the same as null is not the same as the empty string ""the empty string ""

Multiple Multiple AlternativesAlternatives

if (if (condition1condition1))statement1statement1;;

else if (else if (condition2condition2))statement2statement2;;

else if (else if (condition3condition3))statement3statement3;;

elseelsestatement4statement4; ;

The first matching The first matching condition is condition is executed. executed.

Order matters.Order matters.

Page 11: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Earthquake.jEarthquake.javaava11 /** /**

22 A class that describes the effects of an A class that describes the effects of an earthquake. earthquake.

33 */ */ 44 public class Earthquake public class Earthquake 55 { { 66 /** /** 77 Constructs an Earthquake object. Constructs an Earthquake object.

88 @param magnitude the magnitude on @param magnitude the magnitude on the Richter scale the Richter scale

99 */ */ 1010 public Earthquake(double public Earthquake(double

magnitude) magnitude) 1111 { { 1212 richter = magnitude; richter = magnitude; 1313 } }

1515 /** /**

1616 Gets a description of the effect of the Gets a description of the effect of the earthquake. earthquake.

1717 @return the description of the effect @return the description of the effect

1818 */ */

1919 public String getDescription() public String getDescription()

2020 { {

2121 String r; String r;

2222 if (richter >= 8.0) if (richter >= 8.0)

2323 r = "Most structures fall"; r = "Most structures fall";

2424 else if (richter >= 7.0) else if (richter >= 7.0)

2525 r = "Many buildings destroyed"; r = "Many buildings destroyed";

2626 else if (richter >= 6.0) else if (richter >= 6.0)

2727 r = "Many buildings r = "Many buildings considerably considerably damaged, some damaged, some collapse"; collapse";

2828 else if (richter >= 4.5) else if (richter >= 4.5)

2929 r = "Damage to poorly r = "Damage to poorly constructed constructed buildings"; buildings";

3030 else if (richter >= 3.5) else if (richter >= 3.5)

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

3232 else if (richter >= 0) else if (richter >= 0)

3333 r = "Generally not felt by r = "Generally not felt by people"; people";

3434 else else

3535 r = "Negative numbers are not r = "Negative numbers are not valid"; valid";

3636 return r; return r;

3737 } }

3939 private double richter; private double richter;

4040 } }

Page 12: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

EarthquakeTest.javaEarthquakeTest.java11 import javax.swing.JOptionPane; import javax.swing.JOptionPane; 33 /** /** 44 A class to test the Earthquake class. A class to test the Earthquake class. 55 */ */ 66 public class EarthquakeTest public class EarthquakeTest 77 { { 88 public static void main(String[] args) public static void main(String[] args) 99 { { 1010 String input = JOptionPane.showInputDialog( String input = JOptionPane.showInputDialog( 1111 "Enter a magnitude on the Richter "Enter a magnitude on the Richter

scale:"); scale:"); 1212 double magnitude = double magnitude =

Double.parseDouble(input); Double.parseDouble(input); 1313 Earthquake quake = new Earthquake quake = new

Earthquake(magnitude); Earthquake(magnitude); 1414 System.out.println(quake.getDescription()); System.out.println(quake.getDescription());1515 System.exit(0); System.exit(0); 1616 } } 1717 } }

Page 13: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Multiple Multiple AlternativesAlternatives Order matters:Order matters:

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

Don't omit elseDon't omit elseif (richter >= 8.0)if (richter >= 8.0) r = "Most structures fall"; r = "Most structures fall";if (richter >= 7.0) if (richter >= 7.0)

// omitted else--ERROR// omitted else--ERROR r = "Many buildings destroyed r = "Many buildings destroyed

Nested Branches: Nested Branches: Branch inside another branchBranch inside another branch

if (if (condition1condition1)){{ if ( if (condition1acondition1a)) statement1astatement1a;; else else statement1bstatement1b;;}}elseelse statement2statement2;;

Page 14: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

An Example: Tax ReturnAn Example: Tax Return If your filing status is SingleIf your filing status is SingleIf the taxableincome is over

But notover

The tax is Of theamount over

$0 $21,450 15% $0

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

$21,450

$51,900 $11,743.50+ 31%

$51,900

If your filing status is MarriedIf your filing status is Married

If the taxableincome is over

But notover

The tax is Of theamountover

$0 $35,800 15% $0

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

$35,800

$86,500 $19,566.00 + 31%

$86,500

Page 15: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Tax Return: FlowchartTax Return: Flowchart

Page 16: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

TaxReturn.javaTaxReturn.java11 /** /**

22 A tax return of a taxpayer in A tax return of a taxpayer in 1992. 1992.

33 */ */

44 class TaxReturn class TaxReturn

55 { {

66 /** /**

77 Constructs a TaxReturn object Constructs a TaxReturn object for a given income and marital for a given income and marital status. status.

99 @param anIncome the taxpayer @param anIncome the taxpayer incomeincome

1010 @param aStatus either SINGLE @param aStatus either SINGLE or MARRIED or MARRIED

1111 */ */

1212 public TaxReturn(double public TaxReturn(double anIncome, int aStatus) anIncome, int aStatus)

1313 { {

1414 income = anIncome; income = anIncome;

1515 status = aStatus; status = aStatus;

1616 } }

1818 public double getTax() public double getTax()

1919 { {

2020 double tax = 0; double tax = 0;

2121

2222 if (status == SINGLE) if (status == SINGLE)

2323 { {

2424 if (income <= if (income <= SINGLE_CUTOFF1) SINGLE_CUTOFF1)

2525 tax = RATE1 * income;tax = RATE1 * income;

2626 else if (income <= else if (income <=SINGLE_CUTOFF2)SINGLE_CUTOFF2)

2727 tax = SINGLE_BASE2 tax = SINGLE_BASE2

2828 + RATE2 * (income - + RATE2 * (income - SINGLE_CUTOFF1); SINGLE_CUTOFF1);

2929 else else

3030 tax = SINGLE_BASE3 tax = SINGLE_BASE3

3131 + RATE3 * (income - + RATE3 * (income - SINGLE_CUTOFF2); SINGLE_CUTOFF2);

3232 } }

Page 17: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

3333 else else 3434 { { 3535 if if

(income<=MARRIED_CUTOFF1)(income<=MARRIED_CUTOFF1)3636 tax = RATE1 * income; tax = RATE1 * income; 3737 else if else if

(income<=MARRIED_CUTOFF2) (income<=MARRIED_CUTOFF2) 3838 tax = MARRIED_BASE2 tax = MARRIED_BASE2 3939 + RATE2 * (income - + RATE2 * (income -

MARRIED_CUTOFF1); MARRIED_CUTOFF1);

4040 else else 4141 tax = MARRIED_BASE3 tax = MARRIED_BASE3 4242 + RATE3 * (income - + RATE3 * (income -

MARRIED_CUTOFF2); MARRIED_CUTOFF2);

4343 } }4545 return tax; return tax;4646 } } 4848 public static final int SINGLE = 1; public static final int SINGLE = 1;4949 public static final int MARRIED = 2; public static final int MARRIED = 2;5151 private static final double RATE1 = private static final double RATE1 =

0.15; 0.15; 5252 private static final double RATE2 = private static final double RATE2 =

0.28;0.28;5353 private static final double RATE3 = private static final double RATE3 =

0.31;0.31;

5555 private static final double private static final double SINGLE_CUTOFF1 = 21450; SINGLE_CUTOFF1 = 21450;

5656 private static final double private static final double SINGLE_CUTOFF2 = 51900; SINGLE_CUTOFF2 = 51900;

5757

5858 private static final double private static final double SINGLE_BASE2 = 3217.50; SINGLE_BASE2 = 3217.50;

5959 private static final double private static final double SINGLE_BASE3 = 11743.50; SINGLE_BASE3 = 11743.50;

6060 private static final double private static final double MARRIED_CUTOFF1 = MARRIED_CUTOFF1 = 35800;35800;

6161 private static final double private static final double MARRIED_CUTOFF2 = MARRIED_CUTOFF2 = 86500;86500;

6363 private static final double private static final double MARRIED_BASE2 = 5370;MARRIED_BASE2 = 5370;

6464 private static final double private static final double MARRIED_BASE3 = 19566; MARRIED_BASE3 = 19566;

6565

6666 private double income; private double income;

6767 private int status; private int status;

6868 } }

Page 18: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

TaxReturnTest.javaTaxReturnTest.java11 import import

javax.swing.JOptionPane; javax.swing.JOptionPane; 2233 /** /**44 A class to test the TaxReturn A class to test the TaxReturn

class. class. 55 */ */ 66 public class TaxReturnTest public class TaxReturnTest 77 { { 88 public static void main(String[] public static void main(String[]

args) args) 99 { { 1010 String input = String input =

JOptionPane.showInputDialog( JOptionPane.showInputDialog( 1111 "Please enter your income:"); "Please enter your income:"); 1212 double income = double income =

Double.parseDouble(input); Double.parseDouble(input); 1414 input = input =

JOptionPane.showInputDialog(JOptionPane.showInputDialog(1515 "Please enter S "Please enter S

(single) or M (single) or M (married)"); (married)"); 1616 int status = 0; int status = 0;

1818 if (input.equalsIgnoreCase("S")) if (input.equalsIgnoreCase("S")) 1919 status = status =

TaxReturn.SINGLE; TaxReturn.SINGLE; 2020 else if else if

(input.equalsIgnoreCase("M")) (input.equalsIgnoreCase("M")) 2121 status = status =

TaxReturn.MARRIED;TaxReturn.MARRIED;2222 else else 2323 { { 2424

System.out.println("Bad input."); System.out.println("Bad input."); 2525 System.exit(0); System.exit(0); 2626 } } 2828 TaxReturn aTaxReturn = new TaxReturn aTaxReturn = new

TaxReturn(income, status); TaxReturn(income, status); 3030 System.out.println("The tax is " System.out.println("The tax is " 3131 + +

aTaxReturn.getTax()); aTaxReturn.getTax()); 3333 System.exit(0); System.exit(0); 3434 } } 3535 } }

Page 19: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

The boolean TypeThe boolean Type boolean type:boolean type:

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

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

boolean type: one of boolean type: one of these 2 truth values these 2 truth values

Predicate MethodPredicate Method return type return type booleanboolean Example:Example:

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

Use in conditionsUse in conditionsif if (aChecking.isOverdra(aChecking.isOverdrawn()) ... wn()) ...

Useful predicate Useful predicate methods in Character methods in Character class:class:

isDigitisDigitisLetterisLetterisUpperCaseisUpperCaseisLowerCaseisLowerCase

if if (Character.isUpperCa(Character.isUpperCase(ch)) ...se(ch)) ...

boolean Operatorsboolean Operators && and&& and || or|| or ! not! not if (0 < amount && if (0 < amount &&

amount < 1000) ... amount < 1000) ... if (input.equals("S") || if (input.equals("S") ||

input.equals("M")) ...input.equals("M")) ...

Page 20: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

&& and || Operators&& and || Operators

Page 21: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Truth Truth TableTable

ss

A B A && B

true true true

true false falsefalse Any false

A B A || B

true Any truefalse true truefalse false false

A ! A

true false

false true

Page 22: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

De Morgan's LawDe Morgan's Law Negating a complex conditionNegating a complex condition can be confusing: can be confusing:

if (!(0 < amount && amount < 1000)) if (!(0 < amount && amount < 1000)) De Morgan's lawDe Morgan's law states that states that

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

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

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

Note that the Note that the opposite of < is >=opposite of < is >=

Page 23: Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.

Boolean VariablesBoolean Variables private boolean marriedprivate boolean married;; Set to truth value:Set to truth value:

married = input.equals("M");married = input.equals("M"); Use in conditions:Use in conditions:

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

Also called Also called flagflag Don't test Boolean variables against truth Don't test Boolean variables against truth

values--sign of cluelessness:values--sign of cluelessness:if (married == true)if (married == true) // DON'T: // DON'T: if (married)if (married)

if (married == false)if (married == false) // DON'T: // DON'T: if (!if (!married)married)

if (married != false)if (married != false) // NO!!! // NO!!!


Recommended