Multi-Sided Selections

Things To Do First

Things To Do Later

Multi-Sided Ifs

Read!
First, read Chapter 3.5

Multiple-Sided Ifs are a set of if and else blocks that check multiple conditions, usually for a single value. For example, a program might ask the user to choose an option on a text-based menu that lists tasks from 1 to 4. Then the program might want to check the value of the user's choice and run the appropriate program. The multi-sided if will have four different conditions, and when it finds the one condition that is true, that block is executed. The general form of a multi-sided if statement in Java is:

if (expression1) {
	// execute this if expression1 is true
} else if (expression2) {
	// execute this if expression2 is true
} else if (expression3) {
	// execute this if expression3 is true
} else if (expression4) {
	// execute this if expression4 is true
} else {
	// execute this if none of the above are true
}

You can have as many relational expressions as you need in this kind of structure. Notice the single else-block at the bottom: this block is optional and can be used if you want code to execute when none of the conditions applies.

As with the other structures, you can eliminate the braces if there is only one statement in a block.

The "Computing BMI" program section 3.8 show how this kind of if statement works.

Exercises

[Solutions]

  1. The following program determines and displays the letter grade for a student's final grade:
    import java.util.Scanner;
    
    public class GetLetterGrade {
    
        public static void main(String[] args) {
    
            Scanner keysIn = new Scanner(System.in);
            System.out.print("Enter the final grade: ");
            double grade = keysIn.nextDouble();
            String letter = "";
    
            if (grade < 50) {
                letter = "F";
            } else if (grade >= 50) {
                letter = "D";
            } else if (grade >= 60) {
                letter = "C";
            } else if (grade >= 65) {
                letter = "C+";
            } else if (grade >= 70) {
                letter = "B";
            } else if (grade >= 75) {
                letter = "B+";
            } else if (grade >= 80) {
                letter = "A";
            } else if (grade >= 90) {
                letter = "A+";
            }
    
            System.out.println("Letter grade: " + letter);
        }
    }
    1. What would the output be if the user entered a final grade of 48?
    2. What would the output be if the user entered a final grade of 55?
    3. What would the output be if the user entered a final grade of 85?
    4. Why doesn't this program do what it's supposed to do? How would you rewrite it correctly?
  2. 2. Write a Java program that calculates and displays the interest rate for funds that are left on deposit for a certain amount of time. The interest rate is determined by the following chart:
    Years on DepositRate
    5 years or more4.75%
    4 years or more, but less than 5 years4.5%
    3 years or more, but less than 4 years4%
    2 years or more, but less than 3 years3.5%
    1 year or more, but less than 2 years3%
    less than 1 year2.5%
  3. A program needs to display the amount of commission paid to sales people. Commission paid is equal to the amount of sales multiplied by the commission rate. Commission rates are assigned according to the following chart:
    Sales AmountCommission Rate
    under $10005%
    $1000 or more but less than $20007.5%
    $2000 or more, but less than $350010%
    $3500 or more15%

The Switch Statement

Read!
First, read Chapter 3.13

A common structure in many programming languages is the "case" statement. This kind of statement is a lot like a multi-sided selection and in most cases, can be a lot more powerful and efficient than a multi-sided selection. Java's version of a "case" statement is the switch statement.

The switch statement examines one value (usually, but not always a variable) and performs an action or actions based on that value. The switch statement can only examine values that are castable into an int. These include data of type int, byte, short, and char (** see note below). You can't use a switch with any other data type.

The general format of a switch statement is:

switch (variable) {
	case value1:
		// execute if variable = value1
		break;
	case value2:
		// execute if variable = value2
		break;
	case value3:
		// execute if variable = value3
		break;
	default:
		// execute if variable is something else
}

Pay close attention to the syntax of this statement:

You'll also notice the break; statement in each of the case blocks. These are optional, but most of the time you would want to keep them. To see why, run this program:

public class TrySwitch2 {

    public static void main(String[] args) {

        int number = 2;
        switch (number)	{
            case 1:
                System.out.println("one");
            case 2:
                System.out.println("two");
            case 3:
                System.out.println("three");
            default:
                System.out.println("too many!");
        }
    }
}

What output do you expect? What output do you get?

This can actually come in handy:

public class TrySwitch2 {

    public static void main(String[] args) {

        int number = 5;
        switch (number)	{
            case 1:
                System.out.println("only one");
                break;
            case 2:
            case 3:
                System.out.println("a few");
                break;
            case 4:
            case 5:
            case 6:
                System.out.println("a handful");
                break;
            default:
                System.out.println("too many!");
        }
    }
}

Try re-running this program with the values 1, 3, and 9 for the variable number.

Prior to Java 7, you could only use a switch statement with any data type that could be implicitly cast into an int (byte, short, char, and int). In the Java 7 release, the switch statement was given support for String objects:
public class FindProvCode {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        System.out.println("Enter full province/territory name:")
        String province = in.nextLine();
        String provAbbrev = "";

        switch (province.toLowerCase()) {
            case "alberta":  
                provAbbrev = "AB";
                break;
            case "british columbia": 
                provAbbrev = "BC";
                break;
            case "manitoba": 
                provAbbrev = "MB";
                break;
            case "new brunswick": 
                provAbbrev = "NB";
                break;
            case "newfoundland labrador": 
                provAbbrev = "NL";
                break;
            case "nova scotia": 
                provAbbrev = "NS";
                break;
            case "northwest territories": 
                provAbbrev = "NT";
                break;
            case "nunavut": 
                provAbbrev = "NU";
                break;
            case "ontario": 
                provAbbrev = "ON";
                break;
            case "prince edward island":
            case "pei": 
                provAbbrev = "PE";
                break;
            case "quebec": 
                provAbbrev = "QC";
                break;
            case "saskatchewan": 
                provAbbrev = "SK";
                break;
            case "yukon": 
                provAbbrev = "YT";
                break;
        }
        System.out.println("Official abbreviation for " +
            province + ": " + provAbbrev);
    }
}

Exercises

[Solutions]

1. Rewrite the following selection statement as a switch statement:

import java.util.Scanner;

public class IfToSwitch {

    public static void main(String[] args) {

        Scanner keysIn = new Scanner(System.in);
        System.out.println("Enter the shipment status:");
        int status = keysIn.nextInt();

        String action = "";
        if (status == 1) {
            action = "Phone vendor and request delivery.";
        } else if (status == 2) {
            action = "Phone customer and warn of late shipment.";
        } else if (status == 3) {
            action = "Prepare shipping labels.";
        } else if (status == 4)	{
            action = "Order additional product from vendor.";
        } else {
            action = "Error:  Invalid status code.";
        }
        System.out.println(action);
    }
}

2. A restaurant has different specials, depending on the day of the week. Write a program using a switch statement that requests a number from 1 to 7 representing the day of the week (Sunday is 1) and displays the daily special according to the table below:

DaySpecial
SundayRoast Chicken
MondayLasagne
TuesdayPizza
WednesdayHot Wings
ThursdayRoast Chicken
FridayFish and Chips
SaturdayPizza

3. A program is needed to calculate delivery costs to various provinces and territories in Canada. The table below describes how the delivery costs are calculated:

Provinces Abbreviation Delivery Cost
Maritime Provinces
Nova Scotia, New Brunswick, PEINS, NB, PE29.95
Newfoundland & LabradorNL34.95
Central Provinces
Quebec, OntarioQC, ON24.95
Prairie Provinces
Manitoba, SaskatchewanMB, SK29.95
Western Provinces
Alberta, British ColumbiaAB, BC37.95
Territories
Nunavut, Northwest Territories, Yukon TerritoryNU, NT, YT39.95

The user will enter the province's official code abbreviation and the program should display the correct delivery cost.