Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

23
Selection Selection Control Structures Control Structures Chapter 5: Selection Chapter 5: Selection Asserting Java Asserting Java © Rick Mercer © Rick Mercer

Transcript of Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Page 1: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Selection Selection Control StructuresControl Structures

Chapter 5: SelectionChapter 5: SelectionAsserting JavaAsserting Java© Rick Mercer© Rick Mercer

Page 2: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Chapter 5: OutlineChapter 5: Outline

This chapter presents algorithmic patterns that This chapter presents algorithmic patterns that allow alternatives to straight sequential allow alternatives to straight sequential processing:processing:

Guarded ActionGuarded Action execute an action only under certain conditionsexecute an action only under certain conditions

Alternative ActionAlternative Action choose one action or anotherchoose one action or another

Multiple SelectionMultiple Selection choose from more than two sets of actionschoose from more than two sets of actions

Page 3: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

The Guarded Action PatternThe Guarded Action Pattern

Pattern:Pattern: Guarded ActionGuarded Action

Problem:Problem:Execute an action only under certain Execute an action only under certain conditionsconditions

GeneralGeneral if (if (true-or-false-condition true-or-false-condition is true) is true)Form Form execute this set of statementsexecute this set of statements

Code Code if(aStudent.getGPA() >= 3.5)if(aStudent.getGPA() >= 3.5)

Example: Example: deansList.add(aStudent);deansList.add(aStudent);

Page 4: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Flowchart view of guarded actionFlowchart view of guarded action

After the boolean expression of the if statement After the boolean expression of the if statement evaluates, the true-part executes only when the evaluates, the true-part executes only when the boolean expression is true.boolean expression is true.

logicalexpression

False

statement -1

statement-n

TruePart

Page 5: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

The if statement (general form)The if statement (general form)

General form:General form:

if(if(boolean-expressionboolean-expression)) true-parttrue-part ; ; A A boolean-expressionboolean-expression is any expression that is any expression that

evaluates to true or false evaluates to true or false three examples three examples

sales < 15000.00sales < 15000.00 hoursWorked > 40hoursWorked > 40 true || false true || false // read as true or false// read as true or false

Page 6: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Relational OperatorsRelational Operators

boolean expressions often use these relational boolean expressions often use these relational operators:operators:

> Greater than< Less than>= Greater than or equal<= Less than or equal== Equal!= Not equal

Page 7: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

boolean expressionsboolean expressions

Answer true, or falseAnswer true, or false double n1 = 78.0;double n1 = 78.0;

double n2 = 80.0;double n2 = 80.0;

n1 < n2 n1 < n2 // _____// _____

n1 >= n2 n1 >= n2 // _____// _____

(n1 + 35) > n2 (n1 + 35) > n2 // _____// _____

Math.abs(n1-n2) <= 0.001Math.abs(n1-n2) <= 0.001 // _____// _____

n1 == n2 n1 == n2 // _____// _____

n1 != n2 n1 != n2 // _____// _____

Page 8: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

ExamplesExamples

if(grade >= 60)if(grade >= 60) return "Passing";return "Passing";

if(name.indexOf(",") == -1)if(name.indexOf(",") == -1) return "Missing comma";return "Missing comma";

if(str.length() < 2)if(str.length() < 2) return str;return str;

Page 9: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Boolean Operators Boolean Operators

A logical operator (&& means AND) used in an A logical operator (&& means AND) used in an if...else statement:if...else statement:

if((test >= 0) && (test <= 100))if((test >= 0) && (test <= 100)) System.out.println("Test in range");System.out.println("Test in range");

The code evaluates an expression to see if test is The code evaluates an expression to see if test is in the range of 0 through 100 inclusive.in the range of 0 through 100 inclusive.

Page 10: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Truth Tables for Boolean OperatorsTruth Tables for Boolean Operators

Truth tables for the Logical (Boolean) Truth tables for the Logical (Boolean) operators operators !!,, ¦¦, ¦¦, &&&&

Page 11: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

The Alternative Action PatternThe Alternative Action Pattern

Situations arise that require a program to select Situations arise that require a program to select between one set of actions or anotherbetween one set of actions or another

ExamplesExamples withdraw or deposit moneywithdraw or deposit money pass or fail the entrance requirementspass or fail the entrance requirements

This is the Alternative Action PatternThis is the Alternative Action Pattern choose between two alternate sets of actions choose between two alternate sets of actions

Page 12: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Alternative ActionAlternative Action

Pattern:Pattern: Alternative ActionAlternative Action

Problem:Problem: Must choose one action from twoMust choose one action from two alternativesalternatives

Outline:Outline: if (if (true-or-false-condition true-or-false-condition is true) is true) execute action-1execute action-1else else execute action-2execute action-2

CodeCode if(finalGrade >= 60.0)if(finalGrade >= 60.0)

Example:Example: System.out.println("passing"); System.out.println("passing"); elseelse System.out.println("failing");System.out.println("failing");

Page 13: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

if-else General Formif-else General Form

if ( if ( boolean-expression boolean-expression ) ) true-parttrue-part ;; elseelse false-partfalse-part ;;

When the boolean expression evaluates to true, the true-When the boolean expression evaluates to true, the true-part executes and the false-part is disregarded. When the part executes and the false-part is disregarded. When the boolean expression is false, only the false-part executes.boolean expression is false, only the false-part executes.

Page 14: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

The if...else statementThe if...else statement

The if...else statement allows two alternate courses The if...else statement allows two alternate courses of action. of action.

logicalexpression

False

statement-1

statement-n

statement-1

statement-n

True

FalsePart

TruePart

Page 15: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

if...else Example if...else Example

Write the output belowWrite the output below if(sales >= 15000.00)if(sales >= 15000.00)

System.out.println("Bonus="+((sales-15000.0)*0.05));System.out.println("Bonus="+((sales-15000.0)*0.05));

elseelse

System.out.println((15000.0-sales) + " short");System.out.println((15000.0-sales) + " short");

salessales OutputOutput

16000.0016000.00 ________________________________________________________

2000.002000.00 ________________________________________________________

15000.0015000.00 ________________________________________________________

Page 16: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

More Precedence RulesMore Precedence Rules

The following slide summarizes all operators used in The following slide summarizes all operators used in this textbook (we've seen 'em all now)this textbook (we've seen 'em all now)

Precedence: most operators are evaluated (grouped) in a Precedence: most operators are evaluated (grouped) in a left-to-right order:left-to-right order:

a / b / c / da / b / c / d is equivalent tois equivalent to (((a/b)/c)/d)(((a/b)/c)/d)

Assignment operators group in a right-to-left order so the Assignment operators group in a right-to-left order so the expression expression

x = y = z = 0.0 x = y = z = 0.0 is equivalent tois equivalent to (x=(y=(z=0.0))) (x=(y=(z=0.0)))

Page 17: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Operators so far Operators so far chapter 7chapter 7 += -= ++ --+= -= ++ --

Page 18: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Short Circuit Boolean Short Circuit Boolean EvaluationEvaluation

Java boolean expressions evaluate subexpressions in Java boolean expressions evaluate subexpressions in a left to right ordera left to right order

Sometimes the evaluation could stop earlySometimes the evaluation could stop early This expression never evaluates the sqrt of a negative This expression never evaluates the sqrt of a negative

number (it only evaluates what is necessary) :number (it only evaluates what is necessary) : if((x >= 0.0) && (Math.sqrt(x) <= 2.5))if((x >= 0.0) && (Math.sqrt(x) <= 2.5)) // ... // ...

and and test>100 test>100 is not evaluated whenis not evaluated when test<0 test<0 is trueis true if(test < 0 || test > 100)if(test < 0 || test > 100) // ...// ...

Page 19: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Multiple SelectionMultiple Selection

Nested logic:Nested logic: one control structure contains another similar one control structure contains another similar

control structure.control structure. an if...else inside another if...else. an if...else inside another if...else. allows selections from 3 or more alternativesallows selections from 3 or more alternatives

We must often select one alternative from We must often select one alternative from many many

Page 20: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.
Page 21: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Example of Multiple Selection Example of Multiple Selection nested if...elsenested if...else

if(GPA < 3.5)if(GPA < 3.5) System.out.println("Try harder");System.out.println("Try harder"); elseelse if(GPA < 4.0)if(GPA < 4.0) System.out.println("Dean's List");System.out.println("Dean's List"); elseelse System.out.println("President's list");System.out.println("President's list");

GPAGPA Output:Output:

3.03.0 ____________________________________

3.63.6 ____________________________________

4.04.0 ____________________________________

The false part is another if...else

Page 22: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

A Greeting methodA Greeting method

According to the hour of day in European time, 0-23, According to the hour of day in European time, 0-23, Complete method Complete method greetinggreeting to return “Good to return “Good Morning” (0..11), “Good Afternoon” 12..16), “Good Morning” (0..11), “Good Afternoon” 12..16), “Good Evening (17..19) and “Good Night (20..23)” Evening (17..19) and “Good Night (20..23)”

Complete a test method for Complete a test method for String greeting(int)String greeting(int) in ControlFunTest in ControlFunTest

cover all branches (that will be 4) cover all branches (that will be 4) cover all boundaries, which would be the lower bound of each cover all boundaries, which would be the lower bound of each

branch (or the upper bound of each)branch (or the upper bound of each)

Complete Complete String greeting(int)String greeting(int) in ControlFunin ControlFun

Page 23: Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.

Multiple ReturnsMultiple Returns

It is possible to have multiple return statements in a method It is possible to have multiple return statements in a method terminate when the first return executes, terminate when the first return executes, BUT return somethingBUT return something

public String letterGrade() { public String letterGrade() { if(my_percentage >= 90.0)if(my_percentage >= 90.0) return "A";return "A"; if(my_ percentage >= 80.0) if(my_ percentage >= 80.0) return "B";return "B"; if(my_ percentage >= 70.0) if(my_ percentage >= 70.0) return "C";return "C"; if(my_ percentage >= 60.0) if(my_ percentage >= 60.0) return "D";return "D"; if(my_ percentage >= 0.0) if(my_ percentage >= 0.0) return "F"; return "F"; // OOPS! WRONG when percentage < 0// OOPS! WRONG when percentage < 0 }}

Error! You must return something

To fix, remove if(percentage >= 0.0)if(percentage >= 0.0)