1 / 27

Java Programming: From The ground Up

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.out.println("Shipping is $5.00"); }

melina
Télécharger la présentation

Java Programming: From The ground Up

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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.

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

  4. 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.

  5. 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.

  6. The if Statement • An if statement that does not contain curly braces: 1. int max = a; //a is biggest so far 2. if (b > max) // is b bigger than the current maximum 3. max = b; // if so, set max to b 4. if (c > max) // is c bigger than the current maximum? 5. max = c; // if so set max to c 6. 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);

  7. 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 euros2 from euros to dollars: " ); 2. transactionType = input.nextInt(); 3. if (transactionType == 1) // dollars to euros 4. { 5. System.out.print("Number of dollars: "); 6. dollars = input.nextDouble(); 7. euros = dollars/DOLLARS_PER_EURO; 8. System.out.println("Number of euros: " + euros); • } • else // otherwise euros to dollars 11. { 12. System.out.print("Number of euros: "); 13. euros = input.nextDouble(); 14. dollars = euros* DOLLARS_PER_EURO; 15. System.out.println("Number of dollars: " + dollars); 16. }

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

  9. 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.

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

  11. 1. int grade = input.nextInt(); //user supplies a grade 2. if ( grade >=70 ) { if ( grade >= 90) 5. System.out.println( “High pass”); 6. else 7. System.out.println(“Pass”); 8. } 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.” Nested if-else Statements

  12. 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.

  13. 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.

  14. 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.

  15. 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

  16. 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.

  17. The else-if Construction • if (boolean-expression1) • statement-list-1; • else if (boolean-expression2) • 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.

  18. 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");

  19. 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”);

  20. 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.

  21. 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) • { • case casevalue-1: statement; • statement; • … • statement; • break; • case casevalue-2: statement; • statement; • … • statement; • break; • … • case casevalue-n: statement; • statement; • … • statement; • break; • default: statement; • … • statement; • }

  22. 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.

  23. 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.

  24. The switch Statement • Any integer or character expression is permissible: // test1, test 2, and test3 are each integers with values // in the range 0-4. switch( (test1+test2+test3)/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); }

  25. 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.

  26. Craps switch(diceValue) { // 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); }

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

More Related