introduction to computer science decision making –the if statement –the switch statement unit 6

39
Introduction to Computer Science Decision Making the if statement the switch statement Unit 6

Post on 19-Dec-2015

223 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

Introduction to Computer Science

• Decision Making–the if statement

–the switch statement

Unit 6Unit 6

Page 2: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 2

The if statement

• Just like in the robot world, Java needs mechanisms for deciding among several alternative actions

Tax ={0.124 x wages if wages $57600

0.124 x $57600 otherwise

if (wages <= 57600)tax = 0.124 * wages;

elsetax = 0.124 * 57600;

Page 3: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

import intro2cs.utils.*;class SocialSecurity { public static void main (String[ ] args) {

final double MAXIMUM_WAGE = 57600,TAX_RATE = 0.124;

double wages, tax;

SimpleInput sinp = new SimpleInput(System.in); System.out.println(“Wages for Social Security are:$”); wages = sinp.readInt();

if (wages <= MAXIMUM_WAGE) tax = TAX_RATE * wages;

else tax = TAX_RATE * MAXIMUM_WAGE;

System.out.println(“Your Social Security tax is $” + tax);}

}

Page 4: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 4

The Syntax Should be Familiar

if ( condition )

statement-1else

statement-2

The “then” alternative

The “else” alternative

•Each alternative can be a single statement (terminated by a ; ), or a compound statement surrounded by { and }

•The else alternative can be omitted:

if (age >= 18) System.out.println(“You are eligible to vote.”);

Page 5: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 5

Compound Statement Example

if (firstNumber <= secondNumber) {quotient = secondNumber / firstNumber;remainder = secondNumber % firstNumber;

}else {

quotient = firstNumber / secondNumber;remainder = firstNumber % secondNumber;

}

Page 6: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 6

Other Common Constructs;Nested ifs

if ( condition-1 )if ( condition-

2 )

statement-1else

statement-2else

statement-3

•statement-1 is executed if condition-1 and condition-2 are both true

•statement-2 is executed if condition-1 is true and condition-2 is false

•statement-3 is executed if condition-1 is false (no matter what condition-2 is)

Page 7: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 7

if/else Nested in the Else

if ( condition-1 )statement-1

else if

( condition-2 )

statement-2else

statement-3

•statement-1 is executed if condition-1 is true (no matter what condition-2 is)

•statement-2 is executed if condition-1 is false and condition-2 is true

•statement-3 is executed if condition-1 and condition-2 are both false

Page 8: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 8

Cascading ifs

if ( condition-1 )statement-1

else if ( condition-2 )

statement-2else

statement-3

•Same as previous slide, but we’ve changed the indentation to show the logic of the nesting

•First check condition-1, if it’s false, check condition-2, etc.

•This can continue through a whole sequence

Page 9: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 9

More Cascading ifs

if ( condition-1 )statement-1

else if ( condition-2 )statement-2

else if ( condition-3 )statement-3

else if …

elsestatement-n

Page 10: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 10

Example of Cascading ifs

Wind-chillindex ={

temperature wind 4 mph,

(1.6 x temperature) - 55.0 wind > 45 mph.

91.4 - (10.45 + 6.69wind - (0.447 x wind) ) x (91.4 - temperature) / 22.0 4 mph <wind 45 mph,

Page 11: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 11

In Java, that’s…

if (windSpeed <= 4)windChillIndex = temperature;

else if (windSpeed <= 45)windChillIndex =

91.4 - ((10.45+ (6.69 * Math.sqrt(windSpeed))- (0.447 * windSpeed) )* ( (91.4 - temperature) / 22.0));

elsewindChillIndex = (1.6 * temperature)- 55.0;

Page 12: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 12

In Java, that’s…

if (windSpeed <= 4)windChillIndex = temperature;

else if (windSpeed <= 45)windChillIndex =

91.4 - ((10.45+ (6.69 * Math.sqrt(windSpeed))- (0.447 * windSpeed) )* ( (91.4 - temperature) / 22.0));

elsewindChillIndex = (1.6 * temperature)- 55.0;

Page 13: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 13

What about this?

if ( condition-1 )if ( condition-

2 )statement-1

elsestatement-2

•The intention was probably statement-1 if condition-1 and condition-2 are true, statement-2 if condition-1 is false

•THAT’S NOT WHAT HAPPENS!

•The else is matched with the nearest unmatched if

Page 14: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 14

It’s Actually This

if ( condition-1 )if ( condition-

2 )

statement-1else

statement-2

•I just changed the indentation from last slide

•So what actually happens is: statement-1 if condition-1 and condition-2 are true, statement-2 if condition-1 is true and condition-2 is false

•How can we get the other effect, if we want it?

Page 15: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 15

Solution 1

if ( condition-1 ) {if ( condition-

2 )statement-1

}else

statement-2

•Now it’s clear that the else goes with the first if

Page 16: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 16

Solution 2

if ( condition-1 )if ( condition-

2 )

statement-1else;

elsestatement-2

•We put in a “dummy” else statement in the second if

•Now it’s clear that the second else goes with the first if

•Ugly!

Page 17: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 17

Solution 3

if ( ! condition-1 )statement-2

else if ( condition-2 )

statement-1

•Reorganize the code

•Reverse the test

•This is equivalent to:if (condition-1)

{ if (condition-

2) statement-1}else statement-2

Page 18: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 18

Boolean Expressions

• At this point, you hunger for a way of formalizing and organizing all these if, else, nesting, multiple conditions, etc.

• Boolean Expressions to the rescue

• A system for representing a mathematics of true and false

Page 19: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 19

Boolean Expressions

• “Conditions” are called boolean expressions• Boolean expressions are formed by comparing

values with relational operators (below), and combining boolean values with the logical operators || (or), && (and), and ! (not)

Math Java English = == equal to != not equal to < < less than <= less than or equal to > > greater than >= greater than or equal to

Page 20: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 20

Boolean Expressions Make Claims

• lowerLimit > 5

• applicantsAge <= 65

• Let’s say we wanted to check the conditionMINIMUM_WAGE ≤ wages ≤ MAXIMUM_WAGEwe would have to combine two checks:

(MINIMUM_WAGE <= wages) &&(wages <=

MAXIMUM_WAGE)

Page 21: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 21

&&, ||, and ! Truth Tables

! true is false! false is true

&& true false

true true false

false false false

|| true false

true true true

false true false

Page 22: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 22

Simplifications

• Distributive Laws:

(p || r) && (q || r) = (p && q) || r

(p && r) || (q && r) = (p || q) && r

• De Morgan’s Laws:

(! p) && (! q) = ! (p || q)

(! p) || (! q) = ! (p && q)

Page 23: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 23

(! p) && (! q) = ! (p || q)

p q !p !q (!p)&&(!q) (p||q) !(p||q)true true false false false true falsetrue false false true false true falsefalse true true false false true falsefalse false true true true false true

These two columns

are the same

Page 24: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 24

Inclusive or, Exclusive or

• The || version of or is inclusive; if both its arguments are true, the result is true

• Java has an exclusive or, where if both arguments are true, the result is false (“Give me liberty, or give me death”)

^ true false

true false true

false true false

Page 25: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 25

Short-Circuit Evaluation

• Evaluation of boolean expressions goes from left to right, and stops when no more evaluation is necessary to figure out the result:

A && BFirst A is evaluated; if it is false, evaluation stops (since the whole expression is known to be false). Otherwise, B is evaluated, too.

Page 26: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 26

And with ||

• Similarly with ||:A || BFirst A is evaluated; if it is true, evaluation stops (since the whole expression is known to be true). Otherwise, B is evaluated, too.

• Java lets you not do short-circuit evaluation by using | and &

Page 27: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 27

When is this Useful?

• We can make use of short-circuit evaluation:if ( (x != 0) && ( (1/x) > 100) ) {

… }else …

• We don’t have to worry about division by zero; we won’t get to 1/x unless x is not equal to zero.

Page 28: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 28

Example

• Given a year, a month, and a day in

the month, find the number of days

from the beginning of the year to

that day (the “day number”).

• The main problem is to correct for

February, and days that have 30

days instead of 31 days

Page 29: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

dayNumber = ((month - 1) * 31) + day;

// Correct for months beyond Februaryif (month > 2) {

//Assume non-leap yearif ((month == 3) || (month == 4))

dayNumber = dayNumber - 3;else if ((month == 5) || (month == 6))

dayNumber = dayNumber - 4; else if ((month == 7)||(month == 8)||(month == 9))

dayNumber = dayNumber - 5; else if ((month == 10) || (month == 11))

dayNumber = dayNumber - 6; else if (month == 12)

dayNumber = dayNumber - 7;

if ((((year % 4) = 0) && ((year % 100) != 0))|| ((year % 400) == 0))

// Correct for leap year dayNumber = dayNumber + 1;

}

Page 30: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 30

A Simpler (but Magic) Formula;Note use of boolean variable

boolean isLeapYear = ( ((year % 4) == 0)&& ((year % 100) != 0) )

|| ((year % 400) == 0);

// Calculate dayNumber assuming all months have 31 daysdayNumber = ((month - 1) * 31) + day;

// Correct for months beyond Februaryif (month > 2) {

// Assume non-leap yeardayNumber = dayNumber - (((4 * month) + 23) /

10);if (isLeapYear)

// Correct for leap yeardayNumber = dayNumber + 1;

}

Page 31: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 31

More than One Way to Write a Boolean Expression

p q p||q p&&q !(p && q) (p||q) && !(p&&q)true true true true false falsetrue false true false true truefalse true true false true truefalse false false false true false

This column is thesame as p ^ q

Page 32: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 32

Switch Statements

• You can use the switch statement in Java to make a decision based on the value of an integer-valued expression or variable:

switch ( expression ) {statement with case label

statement with case label…

statement with case label}

Page 33: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 33

Use of the Switch

• Each statement is labeled with the keyword case and an integer constant, or the keyword default

• The value of the expression determines where we next execute (based on the case label)

• Execution continues until either the end of the switch statement or a break statement is reached

Page 34: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

Movie Rating Exampleswitch (age) { case 1: case 2: case 3: System.out.println(“Get a babysitter!”); break; case 4: case 5: case 6: case 7: case 8: case 9: System.out.println(“Movies rated G are OK.”);

break; case 10: case 11: case 12: case 13: case 14: case 15: System.out.println(“G or PG movies are OK”);

break; case 16: case 17: System.out.println(“R movies might be OK”);

break; default: System.out.println(“Movies rated R are OK.”);

break;}

Page 35: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 35

How it Works

• For age <= 3, we print the babysitter message

• For age from 4 through 9, the G message is printed

• For ages from 10 through 15, the G or PG message is printed

• For 16 and 17, the “R might be OK” message is printed

• Any other value of agent prints the “R is OK” message

• If there is no “case” for the controlling expression, and no “default”, then nothing is done in the switch statement

Page 36: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 36

Controlling ValueMust be an Integer

• But symbolic constants help make the intent clearstatic final int SUNDAY=1, MONDAY=2, TUESDAY=3, WEDNESDAY=4, THURSDAY=5, FRIDAY=6, SATURDAY=7;int d;…switch (d) { case SUNDAY: System.out.println(“Sunday”); break; case MONDAY: System.out.println(“Monday”); break; case TUESDAY: System.out.println(“Tuesday”); break; case WEDNESDAY: System.out.println(“Wednesday”); break; case THURSDAY: System.out.println(“Thursday”); break; case FRIDAY: System.out.println(“Friday”); break; case SATURDAY: System.out.println(“Saturday”); break;}

Page 37: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 37

Another Example

static final int JANUARY=1, FEBRUARY=2, MARCH=3, APRIL=4, MAY=5, JUNE=6, JULY=7, AUGUST=8, SEPTEMBER=9, OCTOBER=10, NOVEMBER=11, DECEMBER=12;int m, year, numberOfDays;…switch (m) { case FEBRUARY:

if ((((year % 4) == 0) && ((year % 100) != 0)) || ((year % 400) == 0))

numberOfDays = 29;else numberOfDays = 28;break;

case APRIL: case JUNE: case SEPTEMBER: case NOVEMBER: numberOfDays = 30; break; default: numberOfDays = 31;}

Page 38: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 38

The switch as a kind ofif/else expression

switch (expression) {case value-1: statements-1; break;case value-2: statements-2; break; …case value-i: statements-i ; break; default: statements-(i+1)}

switchValue = expression;if (switchValue == value-1) statements-1else if (switchValue == value-2) statements-2…else if (switchValue == value-i) statements-ielse statements-(i+1)

Same execution effects

Page 39: Introduction to Computer Science Decision Making –the if statement –the switch statement Unit 6

6- 39

And if you forget break…

int i = 1;…switch (i) {

case 0: System.out.print(“0”); case 1: System.out.print(“1”); case 2: System.out.print(“2”); case 3: System.out.print(“3”);}System.out.println();

The output 123 will be printed.