Chapter Table of Contents

Ch. 7 Other Selection Structures

Section Table of Contents

Besides if statements, there are also 2 other selection structures you should know about: switch and ternary operator.

Switch

Switch statements allow you to run different blocks of code depending on one variable. This is the general format of a switch statement:

switch (variable) {
			case 1:
						// *do stuff*
			case 2:
						// *do stuff
			...*
			case n:
						// *do stuff
}*

You can use a switch on a variable which is a char, byte, short, int, or String.

It's kind of like conditionals, so why switch? (pun intended)

Switch statements are a more elegant way of using an if-else chain. For example, if you wanted a user to choose from suppose four operations for a calculator, you would only be checking one variable, their choice. You could have them enter a 1 for addition, a 2 for subtraction, a 3 for multiplication, and a 4 for division. Depending on if their choice is 1, 2, 3, or 4, you’ll compute the result in a different way. Let’s look at an example of a basic calculator implemented with a switch statement.

Switch Example

public static void main(String[] args) {
        System.out.println("add | subtract | multiply | divide");

        Scanner input = new Scanner(System.in);
        System.out.print("Enter an operation above: ");
        String operation = input.nextLine().toLowerCase(); // case insensitive
        input.close();

        boolean isOperationValid =
            operation.equals("add") ||
            operation.equals("subtract") ||
            operation.equals("multiply") ||
            operation.equals("divide");

        if (isOperationValid) {
            System.out.print("Enter operand 1: ");
            double operand1 = input.nextDouble();

            System.out.print("Enter operand 2: ");
            double operand2 = input.nextDouble();

            double result = 0; // placeholder
            char operator = ' '; // placeholder
            switch (operation) {
                case "add":
                    result = operand1 + operand2;
                    operator = '+';
                    break;
                case "subtract":
                    result = operand1 - operand2;
                    operator = '-';
                    break;
                case "multiply":
                    result = operand1 * operand2;
                    operator = '*';
                    break;
                case "divide":
                    result = operand1 / operand2;
                    operator = '/';
                    break;
            }
            System.out.println(
                operand1 + " " + operator + " " + operand2 + " = " + result
            );
        } else {
            System.out.println("Sorry, that is not a valid operation.");
        }
    }

Sample output:

add | subtract | multiply | divide
Enter an operation above: divide
Enter operand 1: 20
Enter operand 2: 4
20.0 / 4.0 = 5.0

Explanation

Here the switch variable is a String which is the operation from user input. Depending on what is inputted, the program performs the correct corresponding operation. If the user gives an invalid operation, an error message will print out instead.