Presentation is loading. Please wait.

Presentation is loading. Please wait.

5.3 Multiple Alternatives (Part 1)

Similar presentations


Presentation on theme: "5.3 Multiple Alternatives (Part 1)"— Presentation transcript:

1 5.3 Multiple Alternatives (Part 1)
The multiway if-else statement is simply a normal if-else statement that nests another if-else statement at every else branch It is indented differently from other nested statements All of the Boolean_Expressions are aligned with one another, and their corresponding actions are also aligned with one another The Boolean_Expressions are evaluated in order until one that evaluates to true is found The final else is optional Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

2 Multiway if-else Statement
if (Boolean_Expression) Statement_1 else if (Boolean_Expression) Statement_2 else if (Boolean_Expression_n) Statement_n else Statement_For_All_Other_Possibilities . . . Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

3 Multiway if-else Statement
if (PercentageGrade >= 90) System.out.println(“Your grade is A.”); else if (PercentageGrade >= 80) System.out.println(“Your grade is B.”); else if (PercentageGrade >= 70) System.out.println(“Your grade is C.”); else if (PercentageGrade >= 60) System.out.println(“Your grade is D.”); else System.out.println(“Your grade is F.”); . . . Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

4 The switch Statement The switch statement is the only other kind of Java statement that implements multiway branching When a switch statement is evaluated, one of a number of different branches is executed The choice of which branch to execute is determined by a controlling expression enclosed in parentheses after the keyword switch The controlling expression must evaluate to a char, int, short, or byte Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

5 The switch Statement int vehicleClass; double tool; . . .
switch (vehicleClass) { case 1: System.out.println(“Passenger car.”); toll = 0.50; break; case 2: System.out.println(“Bus.”); toll = 1.50; case 3: System.out.println(“Truck.”); toll = 2.00; default: System.out.println(“Unknown vehicle class!”); } Copyright © 2012 Pearson Addison-Wesley. All rights reserved. 3-5

6 The switch Statement Each branch statement in a switch statement starts with the reserved word case, followed by a constant called a case label, followed by a colon, and then a sequence of statements Each case label must be of the same type as the controlling expression Case labels need not be listed in order or span a complete interval, but each one may appear only once Each sequence of statements may be followed by a break statement ( break;) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

7 The switch Statement There can also be a section labeled default:
The default section is optional, and is usually last Even if the case labels cover all possible outcomes in a given switch statement, it is still a good practice to include a default section It can be used to output an error message, for example When the controlling expression is evaluated, the code for the case label whose value matches the controlling expression is executed If no case label matches, then the only statements executed are those following the default label (if there is one) Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

8 The switch Statement The switch statement ends when it executes a break statement, or when the end of the switch statement is reached When the computer executes the statements after a case label, it continues until a break statement is reached If the break statement is omitted, then after executing the code for one case, the computer will go on to execute the code for the next case If the break statement is omitted inadvertently, the compiler will not issue an error message Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

9 The switch Statement switch (Controlling_Expression) {
case Case_Label_1: Statement_Sequence_1 break; case Case_Label_2: Statement_Sequence_2 case Case_Label_n: Statement_Sequence_n default: Default_Statement Sequence } . . . Copyright © 2012 Pearson Addison-Wesley. All rights reserved.

10 5.3 Multiple Alternatives (Part 2)
Sequences of Comparisons if (condition1) statement1; else if (condition2) statement2; ... else statement4; The first matching condition is executed Order matters: if (richter >= 0) // always passes r = "Generally not felt by people"; else if (richter >= 3.5) // not tested r = "Felt by many people, no destruction"; Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

11 Multiple Alternatives: Sequences of Comparisons
Don’t omit else: if (richter >= 8.0) r = "Most structures fall"; if (richter >= 7.0) // omitted else--ERROR r = "Many buildings destroyed"; Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

12 ch05/quake/Earthquake.java Continued 1 /**
1 /** 2 A class that describes the effects of an earthquake. 3 */ 4 public class Earthquake { 5 private double richter; 6 7 /** Constructs an Earthquake object. @param magnitude the magnitude on the Richter scale */ public Earthquake(double magnitude){ richter = magnitude; } 14 Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

13 ch05/quake/Earthquake.java (cont.)
/** Gets a description of the effect of the earthquake. @return the description of the effect */ public String getDescription() { String r; if (richter >= 8.0) r = "Most structures fall"; else if (richter >= 7.0) r = "Many buildings destroyed"; else if (richter >= 6.0) r = "Many buildings considerably damaged, some collapse"; else if (richter >= 4.5) r = "Damage to poorly constructed buildings"; else if (richter >= 3.5) r = "Felt by many people, no destruction"; else if (richter >= 0) r = "Generally not felt by people"; else r = "Negative numbers are not valid"; return r; } 39 } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

14 ch05/quake/EarthquakeRunner.java Program Run:
1 import java.util.Scanner; 2 3 /** 4 This program prints a description of an earthquake of a given magnitude. 5 */ 6 public class EarthquakeRunner { 7 public static void main(String[] args) { Scanner in = new Scanner(System.in); 9 System.out.print("Enter a magnitude on the Richter scale: "); double magnitude = in.nextDouble(); Earthquake quake = new Earthquake(magnitude); System.out.println(quake.getDescription()); } 15 } Program Run: Enter a magnitude on the Richter scale: 7.1 Many buildings destroyed Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

15 A sequence of if/else if/else that compares a single value
The switch Statement A sequence of if/else if/else that compares a single value against constant alternatives switch (digit) { case 1: System.out.print("one"); break; case 2: System.out.print("two"); break; case 3: System.out.print("three"); break; case 4: System.out.print("four"); break; case 5: System.out.print("five"); break; case 6: System.out.print("six"); break; case 7: System.out.print("seven"); break; case 8: System.out.print("eight"); break; case 9: System.out.print("nine"); break; default: System.out.print("error"); break; } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

16 Multiple Alternatives: Nested Branches
Branch inside another branch: if (condition1) { if (condition2) statement2a; else statement2b; } statement1; Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

17 If your filing status is Single If your filing status is Married
Tax Schedule If your filing status is Single If your filing status is Married Tax Bracket Percentage $0 ... $32,000 10% 0 ... $64,000 Amount over $32,000 25% Amount over $64,000 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

18 Compute taxes due, given filing status and income figure:
Nested Branches Compute taxes due, given filing status and income figure: branch on the filing status for each filing status, branch on income level The two-level decision process is reflected in two levels of if statements We say that the income test is nested inside the test for filing status Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

19 Nested Branches Big Java by Cay Horstmann
Copyright © 2009 by John Wiley & Sons. All rights reserved.

20 ch05/tax/TaxReturn.java Continued 1 /**
1 /** 2 A tax return of a taxpayer in 2008. 3 */ 4 public class TaxReturn { 5 public static final int SINGLE = 1; 6 public static final int MARRIED = 2; 7 8 private static final double RATE1 = 0.10; 9 private static final double RATE2 = 0.25; private static final double RATE1_SINGLE_LIMIT = 32000; private static final double RATE1_MARRIED_LIMIT = 64000; 12 private double income; private int status; 15 Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

21 ch05/tax/TaxReturn.java (cont.)
/** Constructs a TaxReturn object for a given income and marital status. @param anIncome the taxpayer income @param aStatus either SINGLE or MARRIED */ public TaxReturn(double anIncome, int aStatus){ income = anIncome; status = aStatus; } 27 public double getTax() { double tax1 = 0; double tax2 = 0; 31 Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

22 ch05/tax/TaxReturn.java (cont.)
if (status == SINGLE) { if (income <= RATE1_SINGLE_LIMIT) { tax1 = RATE1 * income; } else { tax1 = RATE1 * RATE1_SINGLE_LIMIT; tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT); } } else { if (income <= RATE1_MARRIED_LIMIT) tax1 = RATE1 * income; } else { tax1 = RATE1 * RATE1_MARRIED_LIMIT; tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT); } } 52 return tax1 + tax2; } 55 } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

23 ch05/tax/TaxCalculator.java Continued 1 import java.util.Scanner; 2
3 /** 4 This program calculates a simple tax return. 5 */ 6 public class TaxCalculator { 7 public static void main(String[] args) { Scanner in = new Scanner(System.in); 9 System.out.print("Please enter your income: "); double income = in.nextDouble(); 12 System.out.print("Are you married? (Y/N) "); String input = in.next(); int status; if (input.equalsIgnoreCase("Y")) status = TaxReturn.MARRIED; else status = TaxReturn.SINGLE; TaxReturn aTaxReturn = new TaxReturn(income, status); 21 System.out.println("Tax: " aTaxReturn.getTax()); } 25 } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

24 ch05/tax/TaxCalculator.java (cont.)
Program Run: Please enter your income: 50000 Are you married? (Y/N) N Tax: Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

25 Answer: Yes, if you also reverse the comparisons:
Self Check 5.5 The if/else/else statement for the earthquake strength first tested for higher values, then descended to lower values. Can you reverse that order? Answer: Yes, if you also reverse the comparisons: if (richter < 3.5) r = "Generally not felt by people"; else if (richter < 4.5) r = "Felt by many people, no destruction"; else if (richter < 6.0) r = "Damage to poorly constructed buildings"; ...


Download ppt "5.3 Multiple Alternatives (Part 1)"

Similar presentations


Ads by Google