0

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; } 
1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Is there possibly a different way to write it? Not necessarily a switch statement, just any way other than if statements?
The way you have written it is very common. Note however that you miss the combination that both the white bagel and the wheat bagel have been selected (I'm not sure if that is actually possible in your code).
This update to the question pretty significantly changes what you were asking. Rather than eliminate the original context, it would be better to add on to the question (e.g. "What if my if..else looked like this instead?"), or to ask a new question.
This is a new question entirely, should I mark this one as answered and re ask this question?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.