Chapter 5 - Decisions. Copyright 2014 by John Wiley & Sons. All rights reserved. 1

Chapter 5 - Decisions Copyright © 2014 by John Wiley & Sons. All rights reserved. 1 Chapter Goals To To To To To implement decisions using if st...
Author: Percival Neal
0 downloads 1 Views 946KB Size
Chapter 5 - Decisions

Copyright © 2014 by John Wiley & Sons. All rights reserved.

1

Chapter Goals

To To To To To

implement decisions using if statements compare integers, floating-point numbers, and strings write statements using the boolean data type develop strategies for testing your programs validate user input

Copyright © 2014 by John Wiley & Sons. All rights reserved.

2

The if Statement The if statement allows a program to carry out different actions depending on the nature of the data to be processed. This elevator panel “skips” the thirteenth floor. The floor is not actually missing— the computer that controls the elevator adjusts the floor numbers above 13.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

3

The if Statement Flowchart with two branches

You can include as many statements in each branch as you like. Copyright © 2014 by John Wiley & Sons. All rights reserved.

4

The if Statement Flowchart with one branches if(BooleanExpression) statement; OR if(BooleanExpression) { statement1; statement2; ... }

Block: Set of statements within curly braces

Boolean expression states a condition to be evaluated. Condition always return true or false. If the Boolean expression evaluates to true then the block of code inside the if statement will be executed. If not the first set of code after the end of the if statement (after the closing curly brace) will be executed.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

5

The if Statement When there is nothing to do in the else branch, omit it entirely int actualFloor = floor; if (floor > 13) { actualFloor--; } // No else needed

Copyright © 2014 by John Wiley & Sons. All rights reserved.

6

The if Statement An if statement is like a fork in the road. Depending upon a decision, different parts of the program are executed.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

7

The if-else Statement Flowchart with two branches:

if(BooleanExpression) statement or block 1 else statement or block 2

int actualFloor = floor; if (floor > 13){ actualFloor--; } else{ actualFloor = floor; } Copyright © 2014 by John Wiley & Sons. All rights reserved.

8

The if-else if Statement Test a series of conditions (multiple alternatives) if (BooleanExpression1) statement or block 1 else if(BooleanExpression2) statement or block 2 else statement or block 3 If BooleanExpression1 is true, then statement or block 1 is executed. If BooleanExpression1 is false, then BooleanExpression2 is tested. • If BooleanExpression2 is true, then statement or block 2 is executed. • If BooleanExpression2 is false, then statement or block 3 is executed. You can have as many if-else clauses as is needed.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

9

The if-else if Statement As soon as one of the tests succeeds: • The effect is displayed • No further tests are attempted.

If none of the tests succeed: • The final else clause applies

Copyright © 2014 by John Wiley & Sons. All rights reserved.

10

The if-else if Statement E.g. if (richter >= 8.0) { description = "Most structures fall”; } else if (richter >= 7.0) { description = "Many buildings destroyed”; } else if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } elseif (richter >= 4.5) { description = "Damage to poorly constructed buildings”; } Note that else clause is optional.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

11

The if-else if Statement In this example, must use if/else if/else sequence, not just multiple independent if statements Error: if (richter >= 8.0) // Didn't use else { description = "Most structures fall”; } if (richter >= 7.0) { description = "Many buildings destroyed”; } if (richter >= 6.0) { description = "Many buildings considerably damaged, some collapse”; } if (richter >= 4.5) { "Damage to poorly constructed buildings”; }

The alternatives are no longer exclusive.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

12

Syntax 5.1 The if Statement

Copyright © 2014 by John Wiley & Sons. All rights reserved.

13

section_1/ElevatorSimulation.java 1 import java.util.Scanner; 2 3 /** 4 This program simulates an elevator panel that skips the 13th floor. 5 */ 6 public class ElevatorSimulation 7 { 8 public static void main(String[] args) 9 { 10 Scanner in = new Scanner(System.in); 11 System.out.print("Floor: "); 12 int floor = in.nextInt(); 13 14 // Adjust floor if necessary 15 16 int actualFloor; 17 if (floor > 13) 18 { 19 actualFloor = floor - 1; 20 } 21 else 22 { 23 actualFloor = floor; 24 } 25 Continued 26 System.out.println("The elevator will travel to the actual floor " 27 + actualFloor); 28 } Copyright © 2014 by John Wiley & Sons. All rights reserved. 29 }

14

section_1/ElevatorSimulation.java Program Run: Floor: 20 The elevator will travel to the actual floor 19

Copyright © 2014 by John Wiley & Sons. All rights reserved.

15

Programming Question Write a tester class IfTester to test the use of if condition. In the main method define two variables testScore and grade. testScore represents a score of a student for a given test and should store integer value 76. grade is a character representing the grade of the student based on his/her testScore. Write a set of statements to find and print the grade of the student. Use following criteria for grading: • • • • •

testScore 100-90 80-89 70-79 100) { discountedPrice = originalPrice – 20; } else { discountedPrice = originalPrice – 10; }

What is the discounted price if the original price is : (i) 95? (ii) 100? (iii) 105?

Copyright © 2014 by John Wiley & Sons. All rights reserved.

18

Answer Answer: (i) 85. (ii) 90. (iii) 85.

if (originalPrice > 100) { discountedPrice = originalPrice – 20; } else { discountedPrice = originalPrice – 10; }

Copyright © 2014 by John Wiley & Sons. All rights reserved.

19

Programming Question Modify the IfTester.java to do the following: The variables fuelAmount and fuelCapacity hold the actual amount of fuel and the size of the fuel tank of a vehicle. If less than 10 percent is remaining in the tank, a status light should show a red color; otherwise it shows a green color. Simulate this process by printing out either "red" or "green".

Copyright © 2014 by John Wiley & Sons. All rights reserved.

20

Answer

IfTester.java

Copyright © 2014 by John Wiley & Sons. All rights reserved.

21

Avoid Duplication in Branches If you have duplicate code in each branch, move it out of the if statement. Don't do this: if (floor > 13) { actualFloor = floor – 1; //following statement is a System.out.println("Actual } else { actualFloor = floor; //following statement is a System.out.println("Actual }

Copyright © 2014 by John Wiley & Sons. All rights reserved.

duplicate statement in both if and else floor: " + actualFloor);

duplicate statement in both if and else floor: " + actualFloor);

22

Avoid Duplication in Branches Do this instead: if (floor > 13) { actualFloor = floor – 1; } else { actualFloor = floor; } System.out.println("Actual floor: " + actualFloor);

It will make the code much easier to maintain. Changes will only need to be made in one place.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

23

Comparing Values: Relational Operators In Java, you use a relational operator to check whether one value is greater than another.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

24

Comparing Values: Relational Operators Relational operators compare values:

The == denotes equality testing: floor = 13; // Assign 13 to floor if (floor == 13) // Test whether floor equals 13

Relational operators have lower precedence than arithmetic operators: floor - 1 < 13

is same as (floor – 1) < 13

Copyright © 2014 by John Wiley & Sons. All rights reserved.

25

Syntax 5.2 Comparisons

Copyright © 2014 by John Wiley & Sons. All rights reserved.

26

Programming Question Modify IfTester class to add following 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); }

Explain the output

Copyright © 2014 by John Wiley & Sons. All rights reserved.

27

Answer: Comparing Floating-Point Numbers: Expected output: sqrt(2)squared minus 2 is 0 However, Code prints: sqrt(2)squared minus 2 is not 0 but 4.440892098500626E-16 Why? •

This is due to round-off errors



When comparing floating-point numbers, don’t test for equality. • Check whether they are close enough.

Copyright © 2014 by John Wiley & Sons. All rights reserved.

28

Comparing Floating-Point Numbers To avoid roundoff errors, don't use == to compare floating-point numbers. To compare floating-point numbers test whether they are close enough: |x - y| ≤ ε final double EPSILON = 1E-14; if (Math.abs(x - y)

Suggest Documents