<<

if Statement

• Programs often contain statements that may or may

Flow of Control: Branching not be executed depending on conditions.

(Savitch, Chapter 3) • An if statement checks whether a condition is true before deciding whether to execute some code. TOPICS • Conditions typically involve comparison of variables or • Conditional Execution quantities for equality or inequality. • if, else, and else if • Example: Expression in parenthesis • boolean data must evaluate to either true or false if (age >= 18) • switch statements System.out.println(“You are eligible to vote.”);

CS 160, Summer Semester 2016 1 CS 160, Summer Semester 2016

2

The if Statement Numeric Relational Operators

• The if statement has the following syntax The condition must be a Math Java description boolean expression. It must

if is a Java evaluate to either true or false. < < Less than reserved word > > Greater than if ( condition )

statement; <= Less than or equal to

>= Greater than or equal to

If the condition is true, the statement is executed. = == Equal to If it is false, the statement is skipped.

!= Not equal to

CS 160, Summer Semester 2016 3 CS 160, Summer Semester 2016 4 if Statement with else Defining Blocks

• An if statement may have an optional else • To execute more than one statement conditionally, use { } to define a block (aka “compound statement”) for the sequence of clause that will only be executed when the statements condition is false Give an example of • Example: when BOTH if (firstNumber <= secondNumber) • Example: statements will { execute? quotient = secondNumber / firstNumber; if ( wages <= 57600.0 ) remainder = secondNumber % firstNumber; } tax = 0.124 * wages; NONE!NONE! One or theOne other or the must other else { else executemust execute quotient = firstNumber / secondNumber; tax = 0.124 * 57600.0; remainder = firstNumber % secondNumber; Give an example of } when NEITHER statement will execute? CS 160, Summer Semester 2016 5 CS 160, Summer Semester 2016 6

Cascading if-else Statements Dangling else

• Example: • Code written: • Which if does the if (condition1) if (condition1) else finish?

statement1; if (condition2) else statement1; else will match to the nearest if (condition2) else unmatched if within the same statement2; statement2; block Be sure to use else indentation properly statement3; Otherwise too difficult to read!

CS 160, Summer Semester 2016 7 CS 160, Summer Semester 2016 8 Fix dangling else using blocks boolean Data Type

• Code written: • boolean if (condition1) • A primitive data type that can be set to: { – true if (condition2) NOTE: No quotation – false marks because this statement1; is a boolean, not a • Example: String. } boolean correct = true; else statement2;

CS 160, Summer Semester 2016 9 CS 160, Summer Semester 2016 10

Boolean Expressions boolean Operators

• Conditions are expressions that have a truth • Logical “and” (conjunction) value. – Java symbol && • Arithmetic relational operators produce a – Math symbol ∧ – true only when both expressions are true truth value, e.g., (MINIMUM_WAGE <= wages) && (wages <= MAXIMUM_WAGE) – 10 < 3 • Logical inclusive “or” (disjunction) – x > y – Java symbol || – a >= (b + 12) – Math symbol ∨ – true when either or both expressions are true (wages < MINIMUM_WAGE ) || (wages > MAXIMUM_WAGE )

CS 160, Summer Semester 2016 11 CS 160, Summer Semester 2016 12 Java Logical and Arithmetic boolean Operators (cont.) Operator Precedence Rules

• Logical “exclusive or” Precedence Level Operators

– Java symbol ^ 1. ! - (unary) – Math symbol ⊕ 2. * / % – true when exactly one of the expressions is true 3. + - (MINIMUM_WAGE < wages) ^ (MINIMUM_WAGE == wages) 4. < <= > >=

• Logical “not” (negation) 5. == !=

– Java symbol ! 6. ^ & | – Math symbol ¬ 7. && !(MINIMUM_WAGE == wages) 8. ||

CS 160, Summer Semester 2016 13 CS 160, Summer Semester 2016 14

Complicated Boolean Combining Relational Expressions Operators

boolean isLeapYear = ((year % 4) == 0) • Unlike some other operators, relationals cannot && ((year % 100) != 0) be combined in Java. || ((year % 400) == 0); • Example: (a <= b <= c) Interpretation: – Does not mean a <= b and b <= c. • Leap years are every four years (divisible by 4) – It produces a compile-time error -- cannot compare a except for centuries that are not divisible by 400. boolean (return value of <= operator) with a number. – How should this be done?

( a <= b && b <= c)

CS 160, Summer Semester 2016 15 CS 160, Summer Semester 2016 16 Using break in switch switch Statement statements

• Used to accomplish multi-way branching based on the value • Consider the code fragment below of an integer, character, or string selector variable. int i = 1; switch (i) • Example: { ONLY int, char or String case 0: System.out.println(“0”); switch (numberOfPassengers) case 1: System.out.println(“1”); { break moves case 2: System.out.println(“2”); case 0: System.out.println(“The Harley”); flow of control case 3: System.out.println(“3”); } break; to end of switch case 1: System.out.println(“The Dune Buggy”); System.out.println( ); statement break; 1 default: System.out.println(“The Humvee”); • Without breaks what is the output? 2 } (note: it is legal to leave out the 3 breaks and sometimes desired) default case is Don’t need a break after executed if no other case default – already at end values match expression CS 160, Summer Semester 2016 17 CS 160, Summer Semester 2016 18

Why execute multiple cases? Symbolic Constants in switch Statements

• Consider if you want a base level with add-ons for increasing final int numbers as in… SUNDAY = 1, MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7; switch (zoomember_level) { int d; case 500: System.out.print(“Meet a tiger”); ... case 100: System.out.print(“ Free t-shirt”); switch (d) { case 50: System.out.print(“ Free admission!”); case SUNDAY: System.out.print(“Sunday”); break; default: System.out.println(); case MONDAY: System.out.print(“Monday”); break; } case TUESDAY: System.out.print(“Tuesday”); break;

case WEDNESDAY: System.out.print(“Wednesday”); break; • Example of when we want to leave off the break statements to case THURSDAY: System.out.print(“Thursday”); break; allow execution to follow through case FRIDAY: System.out.print(“Friday”); break; case SATURDAY: System.out.print(“Ski day”); break; }

CS 160, Summer Semester 2016 19 CS 160, Summer Semester 2016 20 Multiple case Labels switch example switch (d) { • Display the students’ grade based on entering their grade as an int between 0 and case MONDAY: 100 (90+ = A, 80-89 = B, 70-79 = C)

case WEDNESDAY: switch( grade / 10 ) case FRIDAY: { System.out.println(“C.S. meets at 9:00 today”); case 10: Integer case 9: division is our System.out.println(“Math meets at 10:00 today”); System.out.println( “A” ); break; break; friend! case TUESDAY: case 8: System.out.println( “B” ); case THURSDAY: break; System.out.println(“English meets at 9:00 today”); case 7: System.out.println(“Chemistry meets at 10:00 today”); System.out.println( “C” ); break; break; default: case SUNDAY: System.out.println( “F” ); case SATURDAY: } System.out.println(“Enjoy the weekend”); }

CS 160, Summer Semester 2016 21 CS 160, Summer Semester 2016 22

Comparing switch and if Comparing switch and if statements statements Print out whether the char ch is a vowel or not

• switch statement • if equivalent • switch statement • if equivalent

switch (letter) { if ( letter == ‘A’ || letter == ‘a’ switch (expression) value = expression; case ‘A’: case ‘a’: || letter == ‘E’ || letter == ‘e’ { if (value == value1) case ‘E’: case ‘e’: case ‘I’: case ‘i’: || letter == ‘I’ || letter == ‘i’ case value1: statement1; statement1; case ‘O’: case ‘o’: || letter == ‘O’ || letter == ‘o’ break; else if (value == value2) case ‘U’: case ‘u’: || letter == ‘U’ || letter == ‘u’ ){ case value2: statement2; statement2; System.out.println( “vowel” ); break; break; System.out.println( “vowel” ); … … default: } else if (value == valueX) System.out.println( “consonant” ); else { case valueX: statementX; statementX; break; } System.out.println( “consonant” ); else default: statementY; } statementY; }

CS 160, Summer Semester 2016 23 CS 160, Summer Semester 2016 24 Summary

• Flow of control • if statements • boolean expressions • if-else statements • Order of operations • Relational operators • switch statement

CS 160, Spring Semester 2016 25