5.3 Multiple Alternatives (Part 1)

Slides:



Advertisements
Similar presentations
DECISIONS Chapter 5. The if Statement  Action based on a conditions  If the condition is true, the body of the statement is executed if (amount
Advertisements

Chapter 5 – Decisions Big Java by Cay Horstmann
Chapter 5 Decisions Goals To be able to implement decisions using if statements To be able to implement decisions using if statements To understand how.
Chapter 5  Decisions 1 Chapter 5 Decisions. Chapter 5  Decisions 2 Chapter Goals  To be able to implement decisions using if statements  To understand.
Chapter 5 – Decisions Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Chapter 3 Flow of Control if-else and switch statements.
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
The switch Statement, DecimalFormat, and Introduction to Looping
Chapter 5: Decisions. To be able to implement decisions using if statements To understand how to group statements into blocks To learn how to compare.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 5 Decisions. Assignments  Written exercises pp 217 – 220 R5.1, R5.3, R5.5, R5.6, R5.9 – R5.15, R5.17, R R5.1, R5.3, R5.5, R5.6, R5.9 –
Chapter Goals To implement decisions using if statements
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Lecture 3 Decisions (Conditionals). One of the essential features of computer programs is their ability to make decisions. Like a train that changes tracks.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 5: Decisions 1 Chapter 5 Decisions.
Fall 2006Slides adapted from Java Concepts companion slides1 Decisions Advanced Programming ICOM 4015 Lecture 5 Reading: Java Concepts Chapter 6.
Copyright © 2012 Pearson Addison-Wesley. All rights reserved. CIS_IS20_CSLO 1. Explain computer programming concepts CSLO1.6. Explain the purpose of general.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
Chapter 6 Decisions. Chapter Goals To be able to implement decisions using if statements To understand how to group statements into blocks To learn how.
Decisions Bush decision making.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
©2016 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved. CSC 110 – INTRO TO COMPUTING - PROGRAMMING Switch Statement.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 5 - Decisions.
A First Book of C++ Chapter 4 Selection.
Introduction to Control Statements IT108 George Mason University.
Control Structures- Decisions. Smart Computers Computer programs can be written to make computers seem smart Making computers smart is based on decision.
CS0007: Introduction to Computer Programming
Switch statement.
Slides by Evan Gallagher
Slides by Evan Gallagher
CNG 140 C Programming (Lecture set 3)
John Woodward A Simple Program – Hello world
SWE 510: Object Oriented Programming in Java
Chapter Goals To implement decisions using if statements
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
Program Control Flow: Making Decision
Chapter 5 – Decisions.
Flow of Control.
Chapter 3 Branching Statements
Nested Branches Nested set of statements: Example: Federal Income Tax
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Chapter 4: Making Decisions.
Chapter 5/6 Decisions.
Control Structures – Selection
Control Statement Examples
Chapter 3 Even More Flow of Control 1
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Chapter 4: Control Structures I (Selection)
© Copyright 2016 by Pearson Education, Inc. All Rights Reserved.
Chapter 5 – Decisions Big Java by Cay Horstmann
Lecture Notes – Week 2 Lecture-2
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
PROGRAM FLOWCHART Selection Statements.
The switch Statement When we want to compare a variable against several values to see which one it has, we can use the switch statement: switch (status)
Chapter 5 – Decisions Big Java by Cay Horstmann
6.2 for Loops Example: for ( int i = 1; i
CprE 185: Intro to Problem Solving (using C)
CSS 161: Fundamentals of Computing
Selection Statements August 22, 2019 ICS102: The course.
Presentation transcript:

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.

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.

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.

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.

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

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.

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.

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.

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.

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.

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.

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 /** 8 Constructs an Earthquake object. 9 @param magnitude the magnitude on the Richter scale 10 */ 11 public Earthquake(double magnitude){ 12 richter = magnitude; 13 } 14 Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

ch05/quake/Earthquake.java (cont.) 17 /** 18 Gets a description of the effect of the earthquake. 19 @return the description of the effect 20 */ 21 public String getDescription() { 22 String r; 23 if (richter >= 8.0) 24 r = "Most structures fall"; 25 else if (richter >= 7.0) 26 r = "Many buildings destroyed"; 27 else if (richter >= 6.0) 28 r = "Many buildings considerably damaged, some collapse"; 29 else if (richter >= 4.5) 30 r = "Damage to poorly constructed buildings"; 31 else if (richter >= 3.5) 32 r = "Felt by many people, no destruction"; 33 else if (richter >= 0) 34 r = "Generally not felt by people"; 35 else 36 r = "Negative numbers are not valid"; 37 return r; 38 } 39 } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

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) { 8 Scanner in = new Scanner(System.in); 9 10 System.out.print("Enter a magnitude on the Richter scale: "); 11 double magnitude = in.nextDouble(); 12 Earthquake quake = new Earthquake(magnitude); 13 System.out.println(quake.getDescription()); 14 } 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.

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.

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.

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.

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.

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

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; 10 private static final double RATE1_SINGLE_LIMIT = 32000; 11 private static final double RATE1_MARRIED_LIMIT = 64000; 12 13 private double income; 14 private int status; 15 Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

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

ch05/tax/TaxReturn.java (cont.) 34 if (status == SINGLE) { 35 if (income <= RATE1_SINGLE_LIMIT) { 36 tax1 = RATE1 * income; 37 } 38 else { 39 tax1 = RATE1 * RATE1_SINGLE_LIMIT; 40 tax2 = RATE2 * (income - RATE1_SINGLE_LIMIT); 41 } 42 } 43 else { 44 if (income <= RATE1_MARRIED_LIMIT) 45 tax1 = RATE1 * income; 46 } 47 else { 48 tax1 = RATE1 * RATE1_MARRIED_LIMIT; 49 tax2 = RATE2 * (income - RATE1_MARRIED_LIMIT); 50 } 51 } 52 53 return tax1 + tax2; 54 } 55 } Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

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) { 8 Scanner in = new Scanner(System.in); 9 10 System.out.print("Please enter your income: "); 11 double income = in.nextDouble(); 12 13 System.out.print("Are you married? (Y/N) "); 14 String input = in.next(); 15 int status; 16 if (input.equalsIgnoreCase("Y")) 17 status = TaxReturn.MARRIED; 18 else 19 status = TaxReturn.SINGLE; 20 TaxReturn aTaxReturn = new TaxReturn(income, status); 21 22 System.out.println("Tax: " 23 + aTaxReturn.getTax()); 24 } 25 } Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

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

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