Top Banner
1 Chapter 5 Branching and Method Algorithm Design
60

1 Chapter 5 Branching and Method Algorithm Design.

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 1 Chapter 5 Branching and Method Algorithm Design.

1

Chapter 5

Branching and

Method Algorithm Design

Page 2: 1 Chapter 5 Branching and Method Algorithm Design.

2

Knowledge Goals

• Understand the Boolean operators AND, OR, and NOT

• Understand the concept of control flow with respect to selection statements

• Understand how nested control flow works• Understand the differences between the if-

else and if-else-if selection structures

Page 3: 1 Chapter 5 Branching and Method Algorithm Design.

3

Knowledge Goals

• Understand the differences between a nested if structure and a series of if structures

• Know when each form of selection structure is appropriate

• Understand the functional decomposition process

Page 4: 1 Chapter 5 Branching and Method Algorithm Design.

4

Skill Goals

• Use the relational operators, <, >, <=. >=, ==, and !=

• Construct a simple logical (Boolean) expression to evaluate a given condition

• Construct a complex Boolean expression to evaluate a given condition

• Construct an if-else statement to perform a specific task

Page 5: 1 Chapter 5 Branching and Method Algorithm Design.

5

Skill Goals

• Construct an if statement to perform a specific task

• Construct a set of nested if statements to perform a specific task

• Apply functional decomposition to design a method algorithm

• Apply testing strategies for if structures• Test and debug a Java application

Page 6: 1 Chapter 5 Branching and Method Algorithm Design.

6

Boolean Expressions

boolean data type

A primitive type consisting of just two values, the constants true and false

We declare variables of type boolean just as we do any other type

boolean hasFever; // true if has high temperature

boolean isSenior; // true if age is at least 65

Page 7: 1 Chapter 5 Branching and Method Algorithm Design.

7

Boolean Expressions

Logical expression

An expression made up of Boolean values and logical operations that evaluates to true or false

A boolean variable or constant An arithmetic expression followed by a relational

operator followed by an arithmetic expression A logical expression followed by a logical

operator followed by a logical expression

Page 8: 1 Chapter 5 Branching and Method Algorithm Design.

8

Relational operators are used in expressions of the form

ExpressionA Operator ExpressionB

temperature > humidity

B*B - 4.0*A*C >= 0.0

one + two < 0

two * three <= four

number == 35

initial != ‘Q’

Boolean Expressions

Page 9: 1 Chapter 5 Branching and Method Algorithm Design.

9

int x, y; x = 4; y = 6;

EXPRESSION VALUE

x < y ?

x + 2 < y ?

x != y ?

x + 3 >= y ?

y == x ?

y == x+2 ?

Page 10: 1 Chapter 5 Branching and Method Algorithm Design.

10

Boolean Expressions

Relational operators can compare values of type charchar first, second;

first < second comes before in collating sequencefirst > second comes after in collating sequence

ASCII collating sequence

Lowercase letters are in sequence

Uppercase letters are in sequence

Digits are in sequence

Uppercase letters precede lowercase letters

Page 11: 1 Chapter 5 Branching and Method Algorithm Design.

11

LeftDigit(s)

3 ” ! “ # $ % & ‘

4 ( ) * + , - . / 0 1

5 2 3 4 5 6 7 8 9 : ;

6 < = > ? @ A B C D E

7 F G H I J K L M N O

8 P Q R S T U V W X Y

9 Z [ \ ] ^ _ ` a b c

10 d e f g h I j k l m

11 n o p q r s t u v w

12 x y z { | } ~

RightDigit Partial ASCII Character Set

0 1 2 3 4 5 6 7 8 9

Page 12: 1 Chapter 5 Branching and Method Algorithm Design.

12

Boolean Expressions

Remember that strings are reference types

myString = “Today”;

yourString = “Today”;

myString == yourSring

returns what?

Page 13: 1 Chapter 5 Branching and Method Algorithm Design.

13

Boolean Expressions

• of implicit type conversions

• of comparing floating-point values for equality and inequality

• of using relational operators with strings

Why are these problems?

Page 14: 1 Chapter 5 Branching and Method Algorithm Design.

14

Boolean Expressions

Method Parameter Returns Operation Performed

Name Type

equals String boolean

compareToString int

Tests for equality of contents

Returns a negative integer if the instance comes before the parameter, a 0 if they are equal, and a positive integer if the parameter comes before the instance

String methods

Page 15: 1 Chapter 5 Branching and Method Algorithm Design.

15

Boolean Expressions

Method Parameter Returns Operation Performed

Name Type

toLowerCase none String

toUpperCase none String

Returns a new identical

string, with the characters all

lowercase

Returns a new identical

string, with the characters all

uppercase.

Page 16: 1 Chapter 5 Branching and Method Algorithm Design.

16

String myState;

String yourState;

myState = “Texas”;

yourState = “Maryland”;

myState.equals(yourState) ?

0 < myState.compareTo(yourState) ?

myState.equals(“Texas”) ?

myState.equals("texas") ?

0 > myState.compareTo(“texas”) ?

yourState.equals("Maryland ") ?

Boolean Expressions

Page 17: 1 Chapter 5 Branching and Method Algorithm Design.

17

Boolean Expressions

Java exp. Logical exp. Meaning

! p NOT p ! p is false if p is true! p is true if p is false

p && q p AND q p && q is true ifboth p and q are true; false otherwise

p || q p OR q p || q is true if eitherp or q or both are true;

false otherwise

Logical Operators

Page 18: 1 Chapter 5 Branching and Method Algorithm Design.

18

100 -13 27grade number

hour

(grade >= 60) ?

(number > 0) ?

(hour >= 0 && hour < 24) ?

(hour == 12 || hour == 0) ?

Boolean Expressions

Page 19: 1 Chapter 5 Branching and Method Algorithm Design.

19

int age;

boolean isSenior, hasFever;

double temperature;

age = 20;

temperature = 102.0;

isSenior = (age >= 65); // isSenior is ?

hasFever = (temperature > 98.6); // hasFever is ?

isSenior && hasFever ?

isSenior || hasFever ?

!isSenior ? !hasFever ?

hasFever && (age > 50) ?

Boolean Expressions

Page 20: 1 Chapter 5 Branching and Method Algorithm Design.

20

Boolean Expressions

int age, height;

age = 25;

height = 70;

!(age < 10) ?

!(height > 60) ?

Page 21: 1 Chapter 5 Branching and Method Algorithm Design.

21

Boolean Expressions

Short-circuit evaluation

Evaluation of a logical expression in left-to-right order with evaluation stopping as soon as the final Boolean value can be determined

Java operators !, &&, and || use short-circuit evaluation

Can you think of examples where short-circuit evaluation saves time?

Page 22: 1 Chapter 5 Branching and Method Algorithm Design.

22

Boolean Expressions

int age, height;

age = 25;

height = 70;

(age > 50) && (height > 60)

false

Evaluation can stop now because result of && is only true when both sides are true; it is already determined that the entire expression will be false

Page 23: 1 Chapter 5 Branching and Method Algorithm Design.

23

Boolean Expressions

int age, height;

age = 25;

height = 70;

(height > 60) || (age > 40)

true

Evaluation can stop now because result of || is true if one side is true; it is already determined that the entire expression will be true

Page 24: 1 Chapter 5 Branching and Method Algorithm Design.

24

Boolean Expressions

int age, weight;

age = 25;weight = 145;

(weight < 180) && (age >= 20)

true Must still be evaluated because truth

value of entire expression is not yet known. Why?

Page 25: 1 Chapter 5 Branching and Method Algorithm Design.

25

Boolean Expressions

int age, height;

age = 25;

height = 70;

!(height > 60)||(age > 50)

true

false

Does this part need to be evaluated?

Page 26: 1 Chapter 5 Branching and Method Algorithm Design.

26

Boolean Expressions

Highest precedence()! unary - unary + ++ --(post)++ -- (pre)* / %+ ‑< <= > >=== !=&&||

= Lowest precedence

Operator Precedence

Relational

Logical

Page 27: 1 Chapter 5 Branching and Method Algorithm Design.

27

Branching

Flow of control

The order in which the computer executes statements

Control structure

A statement used to alter the normally sequential flow of control

Page 28: 1 Chapter 5 Branching and Method Algorithm Design.

28

Branching

Normal flow of control Branching control structure(What is an assertion?)

Page 29: 1 Chapter 5 Branching and Method Algorithm Design.

29

Branching

Page 30: 1 Chapter 5 Branching and Method Algorithm Design.

30

Branching

See how it matches the syntax template?

Page 31: 1 Chapter 5 Branching and Method Algorithm Design.

31

Branching

Calculating pay

Page 32: 1 Chapter 5 Branching and Method Algorithm Design.

32

if (Expression)

Statement1A

else

Statement1B

Statement1A and Statement1B each can be a single statement, a null statement, or a block

Branching

Page 33: 1 Chapter 5 Branching and Method Algorithm Design.

33

Branching

if(Expression)

{

}

else

{

}

“if branch”

“else branch”

Book's formatting style

Page 34: 1 Chapter 5 Branching and Method Algorithm Design.

34

Branching int carDoors, driverAge; float premium, monthlyPayment; . . .

if ((carDoors == 4) && (driverAge > 24)){

premium = 650.00; System.out.println(“Low Risk”);}else{

premium = 1200.00; System.out.println(“High Risk”);}

monthlyPayment = premium / 12.0 + 5.00;

Page 35: 1 Chapter 5 Branching and Method Algorithm Design.

35

What happens if you omit braces?if ((carDoors == 4) && (driverAge > 24))

premium = 650.00;

System.out.println(“Low Risk”);

else

premium = 1200.00;

System.out.println(“High Risk”);

monthlyPayment = premium / 12.0 + 5.00;

COMPILE ERROR OCCURS The “if branch” is the single statement following the if

Branching

Page 36: 1 Chapter 5 Branching and Method Algorithm Design.

36

Branching

Problem

Calculate totalBill where discountRate is .25 and shipCost is 10.00 if purchase is over 100.00Otherwise, discountRate is .10 and shipCost is 5.00

Can you write the code?

Page 37: 1 Chapter 5 Branching and Method Algorithm Design.

37

Branching

if (purchase > 100.00){ discountRate = .25; shipCost = 10.00;}else{ discountRate = .15; shipCost = 5.00;}

totalBill = purchase *(1.0 - discountRate) + shipCost;

Did you get it right?

Page 38: 1 Chapter 5 Branching and Method Algorithm Design.

38

Branching

No braces if branch is a single statement

if (lastInitial <= ‘K’)

volume = 1;

else

volume = 2;

System.out.println(“Look it up in volume # “

+ volume + “ of NYC phone book”);

Page 39: 1 Chapter 5 Branching and Method Algorithm Design.

39

Branching

"Execute or skip"

Page 40: 1 Chapter 5 Branching and Method Algorithm Design.

40

Branching

If taxCode has value ‘T’, increase price by adding

taxRate times price to it

if (taxCode == ‘T’)

price = price + taxRate * price;

Statement can be null statement,single statement, or block

Page 41: 1 Chapter 5 Branching and Method Algorithm Design.

41

Branching

Blockcan

containanothercontrol

structure

Page 42: 1 Chapter 5 Branching and Method Algorithm Design.

42

if (Expression1 )

Statement1

else if (Expression2 )

Statement2...

else if (ExpressionN )

StatementN

else

Statement N+1

Branching

Nested if statements

One and onlyone of thesestatements

will be executed

Page 43: 1 Chapter 5 Branching and Method Algorithm Design.

43

if (creditsEarned >= 90)

{

System.out.print(“Congratulations ”);

System.out.println("Senior Status");

}

else if (creditsEarned >= 60)

System.out.println(“Junior Status”);

else if (creditsEarned >= 30)

System.out.println(“Sophomore Status”);

else

System.out.println(“Freshman Status”);

Branching

Remember, each statement can be acompound statement

Page 44: 1 Chapter 5 Branching and Method Algorithm Design.

44

Branching

What is the outputdouble average;

average = 100.0;

if (average >= 60.0)

if (average < 70.0)

System.out.println(“Marginal PASS”);

else

System.out.println(“FAIL”);

The output is "FAIL". Can you tell why?

Page 45: 1 Chapter 5 Branching and Method Algorithm Design.

45

Branching

Corrected Version

double average;

average = 100.0;

if (average >= 60.0)

{

if(average < 70.0)

System.out.println(“Marginal PASS”);

}

else

System.out.println(“FAIL”);

Page 46: 1 Chapter 5 Branching and Method Algorithm Design.

46

Branching

Compare floating-point values for near equality

double myNumber; double yourNumber;

. . .

if (Math.abs(myNumber - yourNumber) < 0.00001)

System.out.println(“Close enough!”);

Page 47: 1 Chapter 5 Branching and Method Algorithm Design.

47

Branching

Grading scheme

90 - 100 A

80 - 89 B

70 - 79 C

60 - 69 D

below 60 F

Can you writethe

if statement?

Page 48: 1 Chapter 5 Branching and Method Algorithm Design.

48

Branching

if (grade >= 90)

letterGrade = 'A';

else if (grade >= 80)

letterGrade = 'B';

else if (grade >= 70)

letterGrade = 'C';

else if (grade >= 60)

letterGrade = 'D';

else

letterGrade = 'F';

Why don't we have toask if grade < 90 ?

Page 49: 1 Chapter 5 Branching and Method Algorithm Design.

49

Branching

Remember our old friend the Scanner class…

hasNextLine() true if scanner has another line

hasNextInt() true if next token is an int

hasNextDouble()true if next token is a double

We can use these Boolean methods to guard against bad dataif (in.hasNextInt())

value = in.nextInt();

else System.out.println("bad data");

Page 50: 1 Chapter 5 Branching and Method Algorithm Design.

50

Branch Testing

Minimum complete coverage

Execute each branch at least once

Code coverage (white box)

Test data are designed by looking at the code

Data coverage (black box)

Test data chosen without seeing code; based on all possible values for expression

Mixed coverage

Combines code and data coverage

Page 51: 1 Chapter 5 Branching and Method Algorithm Design.

51

Branch Testing

if (grade >= 90)

letterGrade = 'A';

else if (grade >= 80)

letterGrade = 'B';

else if (grade >= 70)

letterGrade = 'C';

else if (grade >= 60)

letterGrade = 'D';

else

letterGrade = 'F';

Code coverage9080706050

Page 52: 1 Chapter 5 Branching and Method Algorithm Design.

52

Branch Testing

if (grade >= 90)

letterGrade = 'A';

else if (grade >= 80)

letterGrade = 'B';

else if (grade >= 70)

letterGrade = 'C';

else if (grade >= 60)

letterGrade = 'D';

else

letterGrade = 'F';

Data coverageall possible values

for grade !Impossible!!

Mixed coverageCode coverage +

< 0>100

Page 53: 1 Chapter 5 Branching and Method Algorithm Design.

53

Method Design

Top-Down Design

Problem-solving technique in which the problem is divided into subproblems; the process is applied to each subproblem

Modules

Self-contained collection of steps, that solve a problem or subproblem

Abstract Step

An algorithmic step containing unspecified details

Concrete Step

An algorithm step in which all details are specified

Page 54: 1 Chapter 5 Branching and Method Algorithm Design.

54

Method Design

1. How would you solve the problem by hand?

2. Write down the major steps

3. If you can write step in Java, it is a concrete step

4. If a module needs a series of smaller steps, it is abstract

5. Give each non-concrete step a name; it becomes a module

6. Repeat process for each abstract module

7. If you are overwhelmed by detail, you have missed a level of abstraction; back up

Page 55: 1 Chapter 5 Branching and Method Algorithm Design.

55

Method Design

Page 56: 1 Chapter 5 Branching and Method Algorithm Design.

56

Method Design

Object-Oriented design (for overall problem)– Focus is on the entities (objects) in a problem

– Begins by identifying the classes of objects in the problem and choosing appropriate operations on those objects

– Programs are collections of objects that communicate with (send messages to) each other

– Data plays a leading role; algorithms are used to implement operations on the objects and to enable interaction of objects with each other

Page 57: 1 Chapter 5 Branching and Method Algorithm Design.

57

Method Design

Functional Decomposition (for methods) Focus is on the sequence of actions (algorithms)

required to solve the problem Begins by breaking the responsibility into a series

of major steps. This process continues until each subproblem cannot be divided further or has an obvious solution

Methods are collections of modules that solve subproblems; a module structure chart (hierarchical solution tree) is often created

Data plays a secondary role as the algorithm is applied to an instance of itself

Page 58: 1 Chapter 5 Branching and Method Algorithm Design.

58

Extras

All theworld

knows myname

What isit and whydo peopleknow it?

Page 59: 1 Chapter 5 Branching and Method Algorithm Design.

59

Extras - GUI Track

Output from JOptionPane.showMessageDialog

Page 60: 1 Chapter 5 Branching and Method Algorithm Design.

60

Extras - GUI Track

Moreoutput