找到你要的答案

Q:How can I change code this to a switch statement?

Q:如何将代码转换为切换语句?

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

编辑:这是配料的代码。我不知道如何打印的名称,在案件超过一个上限被选中。

    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;
    }
answer1: 回答1:

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.

你无法改变这一简单的方式开关语句。如果没有条件匹配,则检查单个变量,并根据该变量的值提供独立的分支,以及可能的默认分支。

在您的情况下,您的逻辑取决于多个变量的状态,而不是单个变量。

你能力为开关语义如通过定义一个新的变量,基于whitebagel其值设置。isselected()然后wheatbagel。isselected(),然后写一个开关的基础上,新的变量。然而,这只会增加复杂性和减少代码的可读性。

更新

你编辑这个问题的方式,这甚至不是一个开关语句的匹配。

java  if-statement  switch-statement