if statement
play

if Statement Programs often contain statements that may or may Flow - PowerPoint PPT Presentation

if Statement Programs often contain statements that may or may Flow of Control: Branching not be executed depending on conditions. An if statement checks whether a condition is true (Savitch, Chapter 3) before deciding whether to execute


  1. if Statement • Programs often contain statements that may or may Flow of Control: Branching not be executed depending on conditions. • An if statement checks whether a condition is true (Savitch, Chapter 3) 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 if (age >= 18) or false • switch statements System.out.println(“You are eligible to vote.”); CS 160, Summer Semester 2016 1 CS 160, Summer Semester 2016 2 Numeric Relational Operators The if Statement • The if statement has the following syntax Math Java description The condition must be a boolean expression. It must if is a Java < Less than < evaluate to either true or false. reserved word > Greater than > if ( condition ) Less than or equal to <= statement ; Greater than or equal to >= = Equal to == If the condition is true, the statement is executed. If it is false, the statement is skipped. Not equal to != CS 160, Summer Semester 2016 3 CS 160, Summer Semester 2016 4

  2. if Statement with else Defining Blocks • To execute more than one statement conditionally, use { } to • An if statement may have an optional else define a block (aka “compound statement”) for the sequence of clause that will only be executed when the statements • Example: condition is false Give an example of 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! else One or the other must One or the other else { execute must 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 else finish? if ( condition1 ) if ( condition1 ) statement1; if ( condition2 ) statement1; else will match else to the nearest else if ( condition2 ) 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

  3. boolean Data Type Fix dangling else using blocks • Code written: • boolean if ( condition1 ) • A primitive data type that can be set to: { – true if ( condition2 ) – false NOTE: No quotation 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 Operators Boolean Expressions • Conditions are expressions that have a truth • Logical “and” (conjunction) value. – Java symbol && – Math symbol ∧ • Arithmetic relational operators produce a – 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 || – Math symbol ∨ – a >= (b + 12) – 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

  4. Java Logical and Arithmetic boolean Operators (cont.) Operator Precedence Rules • Logical “exclusive or” Precedence Level Operators 1. ! - (unary) – Java symbol ^ – 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 • Unlike some other operators, relationals cannot boolean isLeapYear = ((year % 4) == 0) be combined in Java. && ((year % 100) != 0) • Example: || ((year % 400) == 0); (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

  5. 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 switch (numberOfPassengers) case 0: System.out.println(“0”); case 1: System.out.println(“1”); { case 2: System.out.println(“2”); break moves case 0: System.out.println(“The Harley”); case 3: System.out.println(“3”); flow of control } break; to end of switch System.out.println( ); case 1: System.out.println(“The Dune Buggy”); statement break; 1 • Without breaks what is the output? default: System.out.println(“The Humvee”); 2 } 3 (note: it is legal to leave out the 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 Symbolic Constants in switch Why execute multiple cases? Statements final int • Consider if you want a base level with add-ons for increasing SUNDAY = 1, MONDAY = 2, TUESDAY = 3, numbers as in … WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, SATURDAY = 7; switch (zoomember_level) int d; { ... case 500: System.out.print(“Meet a tiger”); switch (d) { case 100: System.out.print(“ Free t-shirt”); 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

  6. Multiple case Labels switch example switch (d) { • Display the students’ grade based on entering their grade as an int between 0 and 100 (90+ = A, 80-89 = B, 70-79 = C) case MONDAY: case WEDNESDAY: switch( grade / 10 ) case FRIDAY: { Integer case 10: System.out.println(“C.S. meets at 9:00 today”); case 9: division is our System.out.println(“Math meets at 10:00 today”); System.out.println( “A” ); friend! break; break; case 8: case TUESDAY: System.out.println( “B” ); case THURSDAY: break; System.out.println(“English meets at 9:00 today”); case 7: System.out.println( “C” ); System.out.println(“Chemistry meets at 10:00 today”); 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’ { case ‘E’: case ‘e’: if (value == value1) 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; System.out.println( “vowel” ); statement2; break; break; System.out.println( “vowel” ); … default: … } else if (value == valueX) System.out.println( else { case valueX: statementX; “consonant” ); statementX; } break; System.out.println( “consonant” ); else default: statementY; } statementY; } CS 160, Summer Semester 2016 23 CS 160, Summer Semester 2016 24

  7. Summary • Flow of control • if statements • boolean expressions • if-else statements • Order of operations • Relational operators • switch statement CS 160, Spring Semester 2016 25

Recommend


More recommend