Java Programming From The ground Up Chapter 4

  • Slides: 27
Download presentation
Java Programming: From The ground Up Chapter 4 Selection and Decision: if Statements

Java Programming: From The ground Up Chapter 4 Selection and Decision: if Statements

The if Statement Example: if (sale < 25. 00) { total += SHIPPING_FEE; System.

The if Statement Example: if (sale < 25. 00) { total += SHIPPING_FEE; System. out. println("Shipping is $5. 00"); } Execution of this statement proceeds as follows: 1. The boolean expression sale < 25. 00 is evaluated. 2. If the boolean expression is true, the two statements enclosed by the curly braces are executed. 3. If the boolean expression is false, the statements enclosed by the braces are skipped.

The if Statement The syntax for an if statement is: if ( boolean-expression) {

The if Statement The syntax for an if statement is: if ( boolean-expression) { statement-1; statement-2; … } statement-n;

The if Statement Terminology: An if statement is also termed a conditional or selection

The if Statement Terminology: An if statement is also termed a conditional or selection statement. The phrase if (boolean-expression) is called the if clause. The boolean expression is also called a boolean condition (or simply a condition). The statement-list enclosed by curly braces is a block or compound statement.

The if Statement A block is a group of statements enclosed by matching curly

The if Statement A block is a group of statements enclosed by matching curly braces. If the statement-list consists of a single statement the braces may be omitted. A single statement without the braces is not considered a block.

The if Statement An if statement that does not contain curly braces: 1. 2.

The if Statement An if statement that does not contain curly braces: 1. 2. 3. 4. 5. 6. int max = a; //a is biggest so far if (b > max) // is b bigger than the current maximum max = b; // if so, set max to b if (c > max) // is c bigger than the current maximum? max = c; // if so set max to c System. out. println (“The maximum value is ” +max); Alternatively, the same fragment can be written using curly braces: int max = a; if (b > max) { max = b; } if (c > max) { max = c; } System. out. println(“The maximum value is “+max);

The if-else Statement The if-else statement provides an alternative: if the boolean condition is

The if-else Statement The if-else statement provides an alternative: if the boolean condition is true one group of statements executes, but if the condition evaluates to false a different group is selected. 1. System. out. print(" 1 to convert from dollars to euros 2 from euros to dollars: " ); 2. transaction. Type = input. next. Int(); 3. 4. 5. 6. 7. 8. if (transaction. Type == 1) // dollars to euros { System. out. print("Number of dollars: "); dollars = input. next. Double(); euros = dollars/DOLLARS_PER_EURO; System. out. println("Number of euros: " + euros); 9. } 10. else // otherwise euros to dollars 11. { 12. System. out. print("Number of euros: "); 13. euros = input. next. Double(); 14. dollars = euros* DOLLARS_PER_EURO; 15. System. out. println("Number of dollars: " + dollars); 16. }

The if-else Statement Lines 12 through 25 constitute a single if-else statement. Line 3

The if-else Statement Lines 12 through 25 constitute a single if-else statement. Line 3 (transaction. Type == 1) is a boolean condition. If this condition is true then the statements on lines 4 through 9 are selected and those on line 10 through 16 are skipped. If the boolean condition is false, then the block consisting of lines 4 through 9 is ignored and the block of statements on lines 10 through 16 executes.

The if-else Statement The syntax of the if else statement is: if (boolean-expression) statement-list-1

The if-else Statement The syntax of the if else statement is: if (boolean-expression) statement-list-1 else statement-list-2 where statement-list-1 and/or statement-list-2 signify single statements or a block. If boolean-expression is true then: statement-list-1 is executed and statement-list-2 is skipped; otherwise, statement-list-1 is skipped and statement-list-2 is executed. Every time an if-else statement is encountered, one of the two statement-lists always executes.

Nested if-else Statements An if-else statement can be nested inside another if-else statement:

Nested if-else Statements An if-else statement can be nested inside another if-else statement:

Nested if-else Statements 1. int grade = input. next. Int(); //user supplies a grade

Nested if-else Statements 1. int grade = input. next. Int(); //user supplies a grade 2. if ( grade >=70 ) 3. { 4. if ( grade >= 90) 5. System. out. println( “High pass”); 6. else 7. System. out. println(“Pass”); 8. } 9. else 10. System. out. println(“Fail”); If the value of grade is 65, the condition on line 2 is false and the corresponding else clause of line 10 executes. The output is “Fail. ” The if-else statement on lines 4 -7 is skipped. If grade is 75, the boolean condition on line 2 is true. As a result, the if-else statement on lines 4 -7 executes and the else clause on line 9 is skipped. Because grade is not greater than or equal to 90, the boolean condition of line 4 is false and the else clause of line 7 executes. The output is “Pass. ” If grade has the value 95, the condition of line 2 is true so the if-else statement of lines 4 -7 executes and the else clause on line 9 is skipped. This time grade is greater than or equal to 90, so the condition on line 4 is true and the println(. . . ) statement on line 5 executes. The output is “High pass. ”

An Ambiguity: The “Dangling else” Problem The code segment: if (a > 1) if

An Ambiguity: The “Dangling else” Problem The code segment: if (a > 1) if (b > 10) System. out. println(“D’oh!”); // says Homer Simpson else System. out. println(“ What’s up, Doc? ”); // says Bugs Bunny contains two if clauses, one else clause, and illustrates a classic ambiguity. Which if clause, (a > 1), or (b > 10), is associated with the single else clause? Two possible interpretations.

An Ambiguity: The “Dangling else” Problem Interpretation 1: if (a > 1) { if

An Ambiguity: The “Dangling else” Problem Interpretation 1: if (a > 1) { if (b > 10) System. out. println( “D’oh!”); // Homer Simpson else System. out. println(“ What’s up, Doc? ”); // Bugs Bunny } The single else clause is paired with the second if clause.

An Ambiguity: The “Dangling else” Problem Interpretation 2: if (a > 1) { if

An Ambiguity: The “Dangling else” Problem Interpretation 2: if (a > 1) { if (b > 10) System. out. println( “D’oh!”); //Homer Simpson } else System. out. println(“ What’s up, Doc? ”); //Bugs Bunny The else clause belongs to the first if clause.

An Ambiguity: The “Dangling else” Problem To emphasize the difference between the two if-else

An Ambiguity: The “Dangling else” Problem To emphasize the difference between the two if-else pairings, consider the following four cases: 1. a = 3; b = 20; 2. a = 3; b = 5; 3. a = 0; b = 20; 4. a = 0; b = 5; With each of the above assignments (1 -4) , interpretation 1 produces the following output: 1. D’oh! 2. What’s up, Doc? 3. //No output is displayed 4. //No output is displayed

An Ambiguity: The “Dangling else” Problem Using the second interpretation, the results are different:

An Ambiguity: The “Dangling else” Problem Using the second interpretation, the results are different: 1. D’oh! 2. //No output is displayed 3. What’s up, Doc? 4. What’s up, Doc? How does Java pair an if with an else? An else is paired with the innemost if. Thus, interpretation 1 is correct.

The else-if Construction if (boolean-expression 1) statement-list-1; else if (boolean-expression 2) statement-list-2; else if

The else-if Construction if (boolean-expression 1) statement-list-1; else if (boolean-expression 2) statement-list-2; else if (boolean-expressionlist-3) statement-list-3; … else statement-list-n; The if clauses are examined sequentially, one after the next. The first time a boolean condition has the value true, the statement (block) attached to that if clause executes and all subsequent code of the nested if-else statement is skipped. If none evaluates to true, the statement attached to the final else clause executes.

The else-if Construction if (score >= 90) System. out. println("Score: "+score+". Your grade is

The else-if Construction if (score >= 90) System. out. println("Score: "+score+". Your grade is an A"); else if (score >= 80) System. out. println("Score: "+score+". Your grade is a B"); else if (score >=70) System. out. println("Score: "+score+". Your grade is a C"); else if (score >=60) System. out. println("Score: "+score+". Your grade is a D"); else System. out. println("Score: "+score+". Your grade is an F");

The switch Statement Java’s switch statement sometimes offers a more compact alternative to the

The switch Statement Java’s switch statement sometimes offers a more compact alternative to the else-if construction. The following else-if segment displays a one-word description for each letter grade ‘A’ through ‘F’: if ( grade == ‘A’) System. out. println(“Excellent”); else if (grade ==’B’) System. out. println(“ Good”); else if (grade ==’C’) System. out. println(“Average”); else if (grade ==’D’) System. out. println(“Passing”); else System. out. println(“Failure”);

The switch Statement The following switch statement accomplishes the same task: switch(grade) { case

The switch Statement The following switch statement accomplishes the same task: switch(grade) { case ‘A’: System. out. println(“Excellent”); break; case ‘B’: System. out. println(“Good”); break; case ‘C’: System. out. println(“Average”); break; case ‘D’: System. out. println(“Passing”); break; default : System. out. println(Failure”); } The value of grade is compared to each “case value” (‘A, ’ ‘B, ’ ‘C, ’ and ‘D’) until a match is found. If one of the case values matches the value of grade, the corresponding println(. . . ) statement executes and the break statement terminates the switch statement. If no case value matches the value of grade then the statement of the default case executes.

The switch Statement The switch statement behaves in a manner similar to the else-if

The switch Statement The switch statement behaves in a manner similar to the else-if construction In its simplest form, the syntax of the switch statement is: switch (switch-expression) { casevalue-1: statement; … statement; break; casevalue-2: statement; … statement; break; … casevalue-n: statement; … statement; break; default: statement; … statement;

The switch Statement The switch statement works as follows: switch-expression is evaluated. The list

The switch Statement The switch statement works as follows: switch-expression is evaluated. The list of case values (casevalue-1, casevalue-2, …, casevalue-n) is searched in order until one of the case values matches the value of switch-expression. If a match is found, the statements associated with that case execute, and the break statement causes the termination of the switch statement. If no match is found, the statements of the default case execute. The default case is optional. If you omit the default case and none of the case values match switch-expression, then the switch statement performs no action. The break statements are also optional.

The switch Statement The value of switch-expression must be an integer or character type;

The switch Statement The value of switch-expression must be an integer or character type; switch-expression cannot evaluate to a floating point or boolean type. The case values must be constants.

The switch Statement Any integer or character expression is permissible: // test 1, test

The switch Statement Any integer or character expression is permissible: // test 1, test 2, and test 3 are each integers with values // in the range 0 -4. switch( (test 1+test 2+test 3)/3) // integer division { case 4: System. out. println(“Grade: A”); break; case 3: System. out. println(“Grade: B”); break; case 2: System. out. println(“Grade: C”); break; case 1: System. out. println(“Grade: D”); break; } default: System. out. println(“Grade: F);

The switch Statement There are circumstances when you might want to omit some break

The switch Statement There are circumstances when you might want to omit some break statements from a switch statement. Roll dice. In craps, If the value shown on a pair of dice is 7 or 11 the player wins. if the value is 2, 3, or 12, the player loses. Any other value is called the player’s “point” and the game is not (yet) resolved.

Craps switch(dice. Value) { // 7 or 11 is a win case 7: case

Craps switch(dice. Value) { // 7 or 11 is a win case 7: case 11: System. out. println(“You rolled “ + value + “ you win!); break; //2, 3, or 12 is a loss case 2: case 3: case 12: System. out. println(“You rolled “+ value + “ you lose!”); break; // 4, 5, 6, 8, 9, or 10 is the “point” } default: System. out. println(“ Your point is“ + value);

The switch Statement An equivalent else-if construction is: if (dice. Value == 7 ||

The switch Statement An equivalent else-if construction is: if (dice. Value == 7 || dice. Value == 11) System. out. println(“You rolled “ + value + “ you win!); else if (dice. Value == 2 || dice. Value == 3 || dice. Value == 12) System. out. println(“You rolled “+ value + “ you lose!”); else System. out. println(“You rolled “ + value + “that’s you point!”);