Chapter 4 Decision Making Lecture Slides to Accompany An Introduction to Computer Science Using Java...

Preview:

Citation preview

Chapter 4Decision Making

Lecture Slides to Accompany

An Introduction to Computer Science Using Java (2nd Edition)

by

S.N. Kamin, D. Mickunas, E. Reingold

Chapter Preview

In this chapter we will:• discuss the use of decision making in

computer programming• describe the use of the Java if and switch

statements• describe the use of Boolean expressions in

Java if statements• discuss the use of integer selector variables

in Java switch statements

if Statement

• Ensures that a statement is executed only when a condition is true

• Conditions typically involve comparison of variables or quantities for equality or inequality

• Example: if (age >= 18)

out.println(“You are eligible to vote.”);

Relational Operators

< < less than

> > greater than

<= less than or equal to

>= greater than or equal to

= == equal to

!= not equal to

if Statement with Optional else

• An if statement may have an optional else clause that will only be executed when the condition is false

• Example:

if (wages <= 57600)

tax = 0.124 * wages;

else

tax = 0.124 * 57600;

Compound Alternatives

• To execute more than one statement conditionally, you may use { } to define a compound statement for either (or both) conditional alternatives

• Example:

if (firstNumber <= secondNumber) {

quotient = secondNumber / firstNumber;

remainder = secondNumber % firstNumber;

}

else {

quotient = firstNumber / secondNumber;

remainder = firstNumber % secondNumber;

}

Cascading if-else Statements

• Example:

if (condition-1)

statement-1;

else

if (condition-2)

statement-2;

else

statement-3;

• Another format:

if (condition-1)

statement-1;

else if (condition-2)

statement-2;

else

statement-3;

Dangling else

• Code written:

if (condition-1)

if (condition-2)

statement-1;

else

statement-2;

• Interpreted as:

if (condition-1)

if (condition-2)

statement-1;

else

statement-2;

Correcting the Problem

• Code written:

if (condition-1) {

if (condition-2)

statement-1;

}

else

statement-2;

• Interpreted as:

if (not condition-1)

statement-2;

else if (condition-2)

statement-1;

Boolean Operators• Logical “and” (conjunction)

– true only when both expressions are true(MINIMUM_WAGE <= wages) && (wages <= MAXIMUM_WAGE)

• Logical inclusive “or” (disjunction)– true when either or both expressions are true(MINIMUM_WAGE < wages) || (MINIMUM_WAGE == wages)

• Logical exclusive “or”– true when exactly one of the expressions is true(MINIMUM_WAGE < wages) ^ (MINIMUM_WAGE == wages)

• Logical “not” (negation)(MINIMUM_WAGE != wages)

Boolean Operator Truth Table

A B A && B A || B A^B !A

True True True True False False

True False False True True False

False True False True True True

False False False False False True

Operator Precedence Rules

1. ! - (unary)

2. * / %

3. + -

4. < <= > >=

5. == !=

6. ^

7. &&

8. ||

Complicated Boolean Expressions

boolean isLeapYear = ((year % 4) == 0)

&& ((year % 100) != 0)

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

// Assume all months have 31 days

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

// Correct for months beyond February

if (month > 2) {

dayNumber = dayNumber - ((4 * month +23) / 10);

if (isLeapYear)

// Correct for leap year

dayNumber = dayNumber + 1;

}

Comparing Strings

• Comparison is done by comparing strings character-by-character left to right, the first character that differs dictates which string is smaller lexicographically

• What if one string is a prefix of the other?– The prefix is smaller than the longer string

• How do upper- and lower-case characters compare?– If a case-sensitive comparison is used lower-case

is always less than upper case• How do special characters (e.g. %) compare?

– Decided by the character ASCII representation

Java String Class Comparison Methods

Example Explanation

int compareTo(String a) Compare two stringslexigraphically, returns<0, ==0, >0 values

int compareToIgnoreCase(String a) Compare two stringslexigraphically, ignoring caseconsiderations

boolean equals(String a) Returns true is the stringsare equal and falseotherwise

Boolan equalsIgnoreCase(String a) Returns true is the stringsare equal, ignoring case, andfalse otherwise

switch Statement• Used to accomplish multi-way branching based on

the value of an integer selector variable• Example:

switch (numberOfPassengers) { case 0: out.println(“The Harley”);

break;

case 1: out.println(“The Dune Buggy”);

break;

default: out.println(“The Humvee”);

}

Why is break used in switch statements?

• Consider the code fragment below

int i = 1; switch (i) {

case 0: out.println(“0”);

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

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

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

}

out.println( );

• Without breaks the output is: 123

Symbolic Constants in switch Statementsfinal int SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7;ind d;...switch (d) { case SUNDAY: out.print(“Sunday”); break; case MONDAY: out.print(“Monday”); break; case TUESDAY: out.print(“Tuesday”); break; case WEDNESDAY: out.print(“Wednesday”); break; case THURSDAY: out.print(“Thursday”); break; case FRIDAY: out.print(“Friday”); break; case SUNDAY: out.print(“Sunday”); break;}

Multiple case Labels in switch Statements

switch (d) { case MONDAY: case WEDNESDAY: case FRIDAY: out.println(“C.S. meets at 9:00 today”); out.println(“Math meets at 10:00 today”); break; case TUESDAY: case THURSDAY: out.println(“English meets at 9:00 today”); out.println(“Chemistry meets at 10:00 today”); break; case SUNDAY: case Saturday out.println(“Enjoy the weekend”);}

Comparing switch and if statements

• switch statement

switch (expression) {

case value-1: statement-1; break;

case value-2: statement-2; break;

case value-i: statement-i; break;

default: statement-(i+1);

}

• if equivalent

switchValue = expression;

if (switchValue == value-1)

statement-1;

else if (switchValue == value-2)

statement-2;

else if (switchValue == value-i)

statement-i;

else

statement-(i+1);

Building Classes with Multiple Methods

public class Classname {

// Author, date, explanation

declarations of public variables

public void methodName ( parameters ) {

declarations of “local” variables

executable statements with relevant comments

}

public void methodName ( parameters ) {

declarations of “local” variables

executable statements with relevant comments

}

}

Recommended