chapter 5– making decisions dr. jim burns. in java, the simplest statement.. is the if(..)...

47
Chapter 5– Making Chapter 5– Making Decisions Decisions Dr. Jim Burns Dr. Jim Burns

Upload: john-jaye

Post on 14-Dec-2015

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Chapter 5– Making DecisionsChapter 5– Making Decisions

Dr. Jim BurnsDr. Jim Burns

Page 2: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

In Java, the simplest statement..In Java, the simplest statement..

Is the if(..) statementIs the if(..) statement

if(someVariable==10) if(someVariable==10) System.out.println(“The value of System.out.println(“The value of someVariable is 10”);someVariable is 10”);

Page 3: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

if(someVariable==10)…if(someVariable==10)…

The if(…) statement evaluates to The if(…) statement evaluates to truetrue when the value of someVariable is 10 and when the value of someVariable is 10 and to to falsefalse when the value of someVariable is when the value of someVariable is not 10not 10

The System.out.println(..) only executes The System.out.println(..) only executes when the if(..) evaluates to truewhen the if(..) evaluates to true

Page 4: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

In if(..) statements the Boolean expression In if(..) statements the Boolean expression must appear within parenthesesmust appear within parentheses

The statement ends after the action to be The statement ends after the action to be taken if the Boolean expression is true is taken if the Boolean expression is true is declareddeclared

Then the semicolon appearsThen the semicolon appears

Page 5: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Irregardless of whether the Boolean Irregardless of whether the Boolean expression is true or false, execution will expression is true or false, execution will continue with the next statementcontinue with the next statement

The System.out.println() statement The System.out.println() statement executes only if the statement is executes only if the statement is truetrue

Page 6: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

The Result of every if(…)The Result of every if(…)

Every if(..) produced a Boolean result…Every if(..) produced a Boolean result…either either truetrue or or falsefalse

Page 7: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Single-alternative if(..)Single-alternative if(..)

if(someVariable==10) if(someVariable==10) System.out.println(“The value of System.out.println(“The value of someVariable is 10”);someVariable is 10”);

Only one action is performed based on the Only one action is performed based on the result of the Boolean expressionresult of the Boolean expression

Page 8: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Dual-alternative if(..)Dual-alternative if(..)

Requires the use of the Requires the use of the else else keywordkeyword

if(someVariable==10) if(someVariable==10) System.out.println(“The value of System.out.println(“The value of someVariable is 10”);someVariable is 10”);

elseelse System.out.println(“No, it’s not”);System.out.println(“No, it’s not”);

Page 9: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Nested IF’sNested IF’s

If(itemsSold > 3)If(itemsSold > 3)

if(totalValue > 1000)if(totalValue > 1000)

bonus = 50;bonus = 50;

elseelse

bonus = 25;bonus = 25;

elseelse

bonus = 10;bonus = 10;

Page 10: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Using Multiple statements in an Using Multiple statements in an if or if…else structureif or if…else structure

Must use braces to designate blocksMust use braces to designate blocks

Page 11: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

If(hoursWorked > 40)If(hoursWorked > 40)

{{

regularPay = 40 * rate;regularPay = 40 * rate;

overtimePay = (hoursWorked – 40) * 1.5 overtimePay = (hoursWorked – 40) * 1.5 * rate* rate

System.out.println(“Regular pay is “ + System.out.println(“Regular pay is “ + regularPay);regularPay);

System.out.println(“Overtime pay is “ + System.out.println(“Overtime pay is “ + overtimePay);overtimePay);

}}

Page 12: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

import javax.swing.JOptionPane;import javax.swing.JOptionPane;public class Payrollpublic class Payroll{{ public static void main(String[] args)public static void main(String[] args) {{ String hoursString;String hoursString; double rate = 20.00;double rate = 20.00; double hoursWorked;double hoursWorked; double regularPay;double regularPay; double overtimePay;double overtimePay; hoursString = JOptionPane.showInputDialog(null,hoursString = JOptionPane.showInputDialog(null, "How many hours did you work this week?");"How many hours did you work this week?"); hoursWorked = Double.parseDouble(hoursString);hoursWorked = Double.parseDouble(hoursString); if(hoursWorked > 40)if(hoursWorked > 40) {{ regularPay = 40 * rate;regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate;overtimePay = (hoursWorked - 40) * 1.5 * rate; }} elseelse {{ regularPay = hoursWorked * rate;regularPay = hoursWorked * rate; overtimePay = 0.0;overtimePay = 0.0; }} JOptionPane.showMessageDialog(null, "Regular pay is " +JOptionPane.showMessageDialog(null, "Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay);regularPay + "\nOvertime pay is " + overtimePay); System.exit(0);System.exit(0); }}

}}

Page 13: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

if(hoursWorked > 40)if(hoursWorked > 40) {{ regularPay = 40 * rate;regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 overtimePay = (hoursWorked - 40) * 1.5

* rate;* rate; }} elseelse {{ regularPay = hoursWorked * rate;regularPay = hoursWorked * rate; overtimePay = 0.0;overtimePay = 0.0; }}

Page 14: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

if(…) cannot ask ..if(…) cannot ask ..

““What number did the user enter?”What number did the user enter?”

INSTEAD…INSTEAD…

““Did the user enter a 1?”Did the user enter a 1?”

““Did the user enter a 2?”Did the user enter a 2?”

““Did the user enter a 3?”Did the user enter a 3?”

Page 15: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Observe the use of Observe the use of elseelse

If(itemsSold > 3)If(itemsSold > 3)

if(totalValue > 1000)if(totalValue > 1000)

bonus = 50;bonus = 50;

elseelse

bonus = 25;bonus = 25;

elseelse

bonus = 10;bonus = 10;

Page 16: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Using logical AND and OR Using logical AND and OR statementsstatements

Rather than nested if’s, can AND two or Rather than nested if’s, can AND two or more Boolean expressions togethermore Boolean expressions together– The result is The result is truetrue only if all Boolean only if all Boolean

expressions are expressions are truetrue

Bonus = 0;Bonus = 0;

If(itemsSold > 3 && totalValue > 1000) If(itemsSold > 3 && totalValue > 1000) bonus = 50;bonus = 50;

Page 17: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

The code above works like…

Bonus = 0;

If(itemsSold > 3)

if(totalValue > 1000)

bonus = 50;

Page 18: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

So why use the && operator??

It makes your code more concise, less error-prone, and easier to understand

Note that when you use the && operator, you must include a complete Boolean expression on each side of the &&

Page 19: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

bonus = 0;

If(itemsSold > 100) bonus = 200;

else if(totalValue > 3000) bonus = 200;

Accomplishes the same as…..

bonus = 0;

If(itemsSold > 100 || totalValue > 3000) bonus = 200;

Page 20: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Avoiding Common errors when Avoiding Common errors when making decisionsmaking decisions

Using the assignment operator instead of Using the assignment operator instead of the comparison operator when testing for the comparison operator when testing for equalityequality

Inserting a semicolon after the Boolean Inserting a semicolon after the Boolean expression in an if statement expression in an if statement

Failing to block a set of statements with Failing to block a set of statements with curly braces when several statements curly braces when several statements depend on the depend on the ifif or the or the elseelse statement statement

Page 21: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Still more common errors…

Failing to include a complete Boolean expression on each side of an && or || operator in an if statement

Performing a range check incorrectly or inefficiently

Using the wrong operator with AND and OR

Page 22: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Performing accurate and Performing accurate and efficient range checksefficient range checks

A range check is a series of A range check is a series of ifif statements statements that determine whether a value falls within that determine whether a value falls within a specified rangea specified range

Page 23: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Incorrect range check code

If(saleAmount >= 1000) commissionRate = .08;

If(saleAmount >= 500) commissionRate = .06;

If(saleAmount <= 499) commissionRate = .05;

Page 24: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Correct range check code…but inefficient

If(saleAmount >= 1000) commissionRate = .08;

else if(saleAmount >= 500) commissionRate = .06;

else if(saleAmount <= 499) commissionRate = 0.05;

.

.

else commissionRate = 0.05;

Page 25: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Using AND and OR Using AND and OR appropriatelyappropriately

The boss might say “Print an error The boss might say “Print an error message when an employee’s hourly rate message when an employee’s hourly rate is under $5.65 and when an employee’s is under $5.65 and when an employee’s hourly pay rate is over $60”hourly pay rate is over $60”

If(payRate < 5.65 && payRate > 60) If(payRate < 5.65 && payRate > 60) System.out.println(“Error in pay rate”);System.out.println(“Error in pay rate”);

What is wrong with this and how do you fix What is wrong with this and how do you fix the problem?the problem?

Page 26: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value
Page 27: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

ANDing two Boolean expressions together

Boolean Expression 1

Boolean

Expression 2

Result of AND ing them

true true true

true false false

false true false

false false false

Page 28: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Both of the Boolean expressions have to be true in order for the result of ANDing them to return a value of true

Page 29: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

ORing two Boolean expressions together

Boolean Expression 1

Boolean

Expression 2

Result of OR ing them

true true true

true false true

false true true

false false false

Page 30: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

When ORing, if either Boolean expression is true, the result of ORing is true.

It’s only when both of the Boolean expressions are false that the result of ORing is false

Page 31: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Using the switch statementUsing the switch statement

if(year == 1) System.out.println(“Freshman”);if(year == 1) System.out.println(“Freshman”);

else if(year == 2) else if(year == 2) System.out.println(“Sophmore”);System.out.println(“Sophmore”);

else if(year == 3) System.out.println(“Junior”);else if(year == 3) System.out.println(“Junior”);

else if(year == 4) System.out.println(“Senior”);else if(year == 4) System.out.println(“Senior”);

else System.out.println(“Invalid year”);else System.out.println(“Invalid year”);

Instead use the switch statement..Instead use the switch statement..

Page 32: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Int year;//get year value from user input or databaseSwitch(year){

case 1:System.out.println(“Freshman”);break;

case 2:System.out.println(“Sophomore”);break;

case 3:System.out.println(“Junior”);break;

case 4:System.out.println(“Senior”);break;

default:System.out.println(“Invalid year”);

}

Page 33: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Int year;//get year value from user input or databaseSwitch(year){

case 1:System.out.println(“Freshman”);

case 2:System.out.println(“Sophomore”);

case 3:System.out.println(“Junior”);

case 4:System.out.println(“Senior”);

default:System.out.println(“Invalid year”);

}

Page 34: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Int year;//get year value from user input or databaseSwitch(year){

case 1:System.out.println(“Freshman”); Break;

case 2:System.out.println(“Sophomore”); Break;

case 3:System.out.println(“Junior”); Break;

case 4:System.out.println(“Senior”); Break;

default:System.out.println(“Invalid year”);

Page 35: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

In the code above….

The switch structure begins by evaluating the year variable in the switch statement

If year is equal to the first case value, which is one, “Freshman” is printed

The break statements bypass the rest of the switch structure and execution continues with the statement following the closing curly brace of the switch structure

Page 36: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

switch()

What is the data type of the argument of a switch() statement?

Int, char, short and byte

Does a semicolon follow a switch statement?

What delimiter follows each case statement?

Are the break statements necessary for the code to work right?

Page 37: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

int department;int department;

String supervisor;String supervisor;

// Statement to get department value// Statement to get department value

Switch (department)Switch (department)

{{

case 1:case 1:

case 2:case 2:

case 3:case 3:

supervisor = “Jones”;supervisor = “Jones”;

Break;Break;

case 4:case 4:

supervisor = “Staples”;supervisor = “Staples”;

Page 38: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

break;break;

case 5;case 5;

supervisor = “Tejano”;supervisor = “Tejano”;

break;break;

default:default:

System.out.println(“Invalid System.out.println(“Invalid department code”);department code”);

}}

Page 39: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Using the conditional AND NOT Using the conditional AND NOT OperatorsOperators

Page 40: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Consider the following code…Consider the following code…

If(a < b) smallerNum = a;If(a < b) smallerNum = a;

else smallerNum = b;else smallerNum = b;

smallerNum = (a < b) ? A : b;smallerNum = (a < b) ? A : b;

The conditional operator uses the ? and the : to The conditional operator uses the ? and the : to separate three expressions; the first expression separate three expressions; the first expression must be a Boolean expressionmust be a Boolean expression

Page 41: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Using the NOT OperatorUsing the NOT Operator

You use the NOT operator which is written You use the NOT operator which is written as the exclamation point (!), to negate the as the exclamation point (!), to negate the result of any Boolean expressionresult of any Boolean expression

If (age <= 25) premium = 200;If (age <= 25) premium = 200;

else premium = 125;else premium = 125;

If(!(age <= 25)) premium = 125;If(!(age <= 25)) premium = 125;

else premium = 200;else premium = 200;

Page 42: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Understanding precedenceUnderstanding precedencePrecedence Operator(s) Symbols

Highest Logical NOT !

Intermediate Multiplication, division, modulus

* / %

Addition, subtraction + -

Relational > < >= <=

Equality == !=

Logical AND &&

Logical OR ||

Conditional ? :

lowest Assignment =

Page 43: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

PrecedencePrecedence

Order of precedence agrees with common Order of precedence agrees with common algebraic practicealgebraic practice

Notice that the and && operator is always Notice that the and && operator is always evaluated before the or || operatorevaluated before the or || operator

Page 44: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

ExampleExampleConsider an auto insurance sys that determines Consider an auto insurance sys that determines the amount of premium to chargethe amount of premium to charge

Additional premium is charged to a driver who Additional premium is charged to a driver who meets both of the following criteria:meets both of the following criteria:– Has more than two traffic tickets or is under 25 years Has more than two traffic tickets or is under 25 years

oldold– Is maleIs male

Consider a 30 year old female driver with three Consider a 30 year old female driver with three traffic ticketstraffic tickets

Page 45: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Code implementations

// assigns extra premiums incorrectly

if(trafficTickets > 2 || age < 25 && gender == ‘M’) extraPremium = 200;

// assigns extra premiums correctly

If((trafficTickets > 2 || age < 25) && gender == ‘M’) extraPremium = 200;

Remember, do what is inside () first

Page 46: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

import javax.swing.JOptionPane;public class Payroll{ public static void main(String[] args) { String hoursString; double rate = 20.00; double hoursWorked; double regularPay; double overtimePay; hoursString = JOptionPane.showInputDialog(null, "How many hours did you work this week?"); hoursWorked =

Page 47: Chapter 5– Making Decisions Dr. Jim Burns. In Java, the simplest statement.. Is the if(..) statement if(someVariable==10) System.out.println(“The value

Double.parseDouble(hoursString); if(hoursWorked > 40) { regularPay = 40 * rate; overtimePay = (hoursWorked - 40) * 1.5 * rate; } else { regularPay = hoursWorked * rate; overtimePay = 0.0; } JOptionPane.showMessageDialog(null, "Regular pay is " + regularPay + "\nOvertime pay is " + overtimePay); System.exit(0); }}