PrettyNovice
PrettyNovice

Reputation: 15

How can I change code this to a switch statement?

EDIT: Here is the code for the toppings. I'm not sure how to print the names out in the case that more than one topping is selected.

    public double getToppingCost()
    {

        double toppingCost = 0.0;


        if (creamCheese.isSelected())
            toppingCost += CREAM_CHEESE;
        if (butter.isSelected())
            toppingCost += BUTTER;
        if (peachJelly.isSelected())
            toppingCost += PEACH_JELLY;
        if (blueberryJam.isSelected())
            toppingCost += BLUEBERRY_JAM;
        if (nutella.isSelected())
            toppingCost += NUTELLA;


        return toppingCost;
    }

Upvotes: 0

Views: 64

Answers (1)

Eric J.
Eric J.

Reputation: 150108

You cannot change this to a switch statement in a straighforward manner. Switch examines a single variable and provides separate case branches based on the value of that single variable, as well as a possible default branch if none of the conditions match.

In your case, your logic depends on the state of multiple variables, not of a single variable.

You could force this into a switch semantic e.g. by defining a new variable and setting its value based on whiteBagel.isSelected() and then wheatBagel.isSelected(), and then writing a switch based on that new variable. However, this would only add complexity and reduce readability of the code.

UPDATE

The way you have edited the question, this is even less a match for a switch statement.

Upvotes: 2

Related Questions