1 chapter 5 branching and method algorithm design

60
1 Chapter 5 Branching and Method Algorithm Design

Post on 20-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

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

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

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

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

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

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

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

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 ?

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

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

12

Boolean Expressions

Remember that strings are reference types

myString = “Today”;

yourString = “Today”;

myString == yourSring

returns what?

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?

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

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.

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

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

18

100 -13 27grade number

hour

(grade >= 60) ?

(number > 0) ?

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

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

Boolean Expressions

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

20

Boolean Expressions

int age, height;

age = 25;

height = 70;

!(age < 10) ?

!(height > 60) ?

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?

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

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

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?

25

Boolean Expressions

int age, height;

age = 25;

height = 70;

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

true

false

Does this part need to be evaluated?

26

Boolean Expressions

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

= Lowest precedence

Operator Precedence

Relational

Logical

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

28

Branching

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

29

Branching

30

Branching

See how it matches the syntax template?

31

Branching

Calculating pay

32

if (Expression)

Statement1A

else

Statement1B

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

Branching

33

Branching

if(Expression)

{

}

else

{

}

“if branch”

“else branch”

Book's formatting style

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;

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

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?

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?

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

39

Branching

"Execute or skip"

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

41

Branching

Blockcan

containanothercontrol

structure

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

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

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?

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

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

47

Branching

Grading scheme

90 - 100 A

80 - 89 B

70 - 79 C

60 - 69 D

below 60 F

Can you writethe

if statement?

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 ?

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

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

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

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

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

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

55

Method 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

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

58

Extras

All theworld

knows myname

What isit and whydo peopleknow it?

59

Extras - GUI Track

Output from JOptionPane.showMessageDialog

60

Extras - GUI Track

Moreoutput