Topic 12 Conditional Execution "We flew down weekly to meet with IBM, but they thought the way to measure software Conditional execution with if was the amount of code we wrote, when statements really the better the software, the fewer lines of code." -Bill Gates Based on slides for Building Java Programs by Reges/Stepp, found at http://faculty.washington.edu/stepp/book/ CS305j Introduction to Conditional Execution 1 2 Computing The if statement The if/else statement � Programs that read user input often want to take different � if/else statement : A Java statement that executes one block of statements if a certain condition is true, and a second block of actions depending on the values of the user's input. statements if the condition is not true. � if statement : A Java statement that executes a block of – General syntax: if ( <condition> ) { statements only if a certain condition is true. <statement(s)> ; – If the condition is not true, the block of statements is skipped. } else { – General syntax: <statement(s)> ; if ( <condition> ) { } <statement(s)> ; – Example: } double gpa = console.nextDouble(); if (gpa <= 2.0) { – Example: System.out.println("Your application is denied."); double gpa = console.nextDouble(); } if (gpa <= 2.0) { else { System.out.println("Your application is denied."); System.out.println("Welcome to Mars University!"); } } CS305j Introduction to Conditional Execution 3 CS305j Introduction to Conditional Execution 4 Computing Computing
Relational expressions Evaluating relational expressions � The <condition> used in an if or if/else statement is � The relational operators can be used in a bigger expression the same kind of value seen in the middle of a for loop. with the mathematical operators we learned earlier. – for (int i = 1; i <= 10 ; i++) � Relational operators have a lower precedence than mathematical operators, so they are evaluated last. � These conditions are called relational expressions . – Example: � Relational expressions use one of the following six 5 * 7 >= 3 + 5 * (7 - 1) relational operators : 5 * 7 >= 3 + 5 * 6 35 >= 3 + 30 35 >= 33 Operator Meaning Example Value true == equals 1 + 1 == 2 true � Relational operators cannot be "chained" in the way that you != does not equal 3.2 != 2.5 true have seen in algebra. < less than 10 < 5 false – Example: > greater than 10 > 5 true 2 <= x <= 10 <= less than or equal to 126 <= 100 false true <= 10 >= greater than or equal to 5.0 >= 5.0 true error! CS305j Introduction to Conditional Execution CS305j Introduction to Conditional Execution 5 6 Computing Computing Nested if/else statements Structures of if/else code � Nested if/else statement : A chain of if/else that can select between many different outcomes based on several conditions. � Choose 1 of many paths: � Choose 0 or 1 of many paths: – General syntax (shown with three different outcomes, but any number of (use this when the conditions are mutually (use this when the conditions are mutually else if statements can be added in the middle): exclusive) exclusive and any action is optional) if ( <condition> ) { if ( <condition> ) { if ( <condition> ) { <statement(s)> ; <statement(s)> ; <statement(s)> ; } else if ( <condition> ) { } else if (<condition>) { } else if ( <condition> ) { <statement(s)> ; <statement(s)> ; <statement(s)> ; } else { } else if (<condition>) { } else { <statement(s)> ; <statement(s)> ; <statement(s)> ; } } } � Choose 0, 1, or many of many paths: – Example: (use this when the conditions/actions are independent of each other) int grade = console.nextInt(); if ( <condition> ) { if (grade >= 90) { <statement(s)> ; System.out.println("Congratulations! An A!"); } } else if (grade >= 80) { if ( <condition> ) { System.out.println("Your grade is B. Not bad."); <statement(s)> ; } else if (grade >= 70) { } System.out.println("You got a C. Work harder!"); if ( <condition> ) { } <statement(s)> ; } CS305j Introduction to Conditional Execution 7 CS305j Introduction to Conditional Execution 8 Computing Computing
How to comment: if/else How to comment: if/else 2 � Comments on an if statement don't need to describe exactly what the if � If an if statement's test is straightforward, and if the actions statement is testing. to be taken in the bodies of the if/else statement are very – Instead, they should describe why you are performing that test, and/or what different, sometimes putting comments on the bodies you intend to do based on its result. – Poor style: themselves is more helpful. // Test whether student 1's GPA is better than student 2's if (gpa1 > gpa2) { – Example: // print that student 1 had the greater GPA if (guessAgain.equals("y")) { System.out.println("The first student had the greater GPA."); // user wants to guess again; reset game state and } else if (gpa2 > gpa1) { // print that student 2 had the greater GPA // play another game System.out.println("The second student's GPA was higher."); System.out.println("Playing another game."); } else { score = 0; // there was a tie System.out.println("There has been a tie!"); resetGame(); } play(); – Good style: } else { // Print a message about which student had the higher grade point average. // user is finished playing; print their best score if (gpa1 > gpa2) { System.out.println("Thank you for playing."); System.out.println("The first student had the greater GPA."); } else if (gpa2 > gpa1) { System.out.println("Your score was " + score); System.out.println("The second student's GPA was higher."); } } else { // gpa1 == gpa2 (a tie) System.out.println("There has been a tie!"); } CS305j Introduction to Conditional Execution CS305j Introduction to Conditional Execution 9 10 Computing Computing Math.max/min vs. if/else Factoring if/else code � Many if/else statements that choose the larger or smaller of � factoring : extracting a common part of code to reduce 2 numbers can be replaced by a call to Math.max or redundancy Math.min . – factoring if/else code reduces the size of the if and else statements – int z; // z should be larger of x, y and can sometimes eliminate the need for if/else altogether. if (x > y) { – example: z = x; } else { int x; z = y; if (a == 1) { } – int z = Math.max(x, y); x = 3; – double d = a; // d should be smallest of a, b, c } else if (a == 2) { if (b < d) { int x = 2 * a + 1; x = 5; d = b; } else { // a == 3 } x = 7; if (c < d) { d = c; } } – double d = Math.min(a, Math.min(b, c)); CS305j Introduction to Conditional Execution 11 CS305j Introduction to Conditional Execution 12 Computing Computing
Code in need of factoring Code after factoring � The following example has a lot of redundant code in the if/else: � If the beginning of each if/else branch is essentially the same, try to move it out before the if/else. If the end of each if/else branch is the if (money < 500) { same, try to move it out after the if/else. System.out.println("You have, $" + money + " left."); System.out.print("Caution! Bet carefully."); System.out.println("You have, $" + money + " left."); System.out.print("How much do you want to bet? "); bet = console.nextInt(); if (money < 500) { } else if (money < 1000) { System.out.print("Caution! Bet carefully."); System.out.println("You have, $" + money + " left."); } else if (money < 1000) { System.out.print("Consider betting moderately."); System.out.print("Consider betting moderately."); System.out.print("How much do you want to bet? "); } else { bet = console.nextInt(); System.out.print("You may bet liberally."); } else { } System.out.println("You have, $" + money + " left."); System.out.print("You may bet liberally."); System.out.print("How much do you want to bet? "); System.out.print("How much do you want to bet? "); bet = console.nextInt(); bet = console.nextInt(); } CS305j Introduction to Conditional Execution CS305j Introduction to Conditional Execution 13 14 Computing Computing Practice methods � Write a method to determine the max value, given three integers � Write a method determines if 2 points form a line and if so if it is a vertical line, horizontal line, or neither � Write a method to determine the number of times the character 'm' occurs in a String � Generalize the previous method to determine the number of times any given character occurs in a String � Write a method that determines the last index of a character in a given String CS305j Introduction to Conditional Execution 15 Computing
Recommend
More recommend