【问题标题】:Boolean value not being initialized with Constructor未使用构造函数初始化布尔值
【发布时间】:2019-11-23 03:45:13
【问题描述】:

我创建了一个简单的系统来创建汉堡包,您可以在其中添加成分,然后根据您选择的成分计算价格,基本价格为 5,没有额外的成分,对于您想要更多的每种成分,我将其值设置为true 并且我有一个价格计数器,它将在基本价格上增加 1 欧元/美元,这里的问题是布尔字段没有被启动为 false,即使我在类 Constructor 中设置它,我也不能明白为什么。

我尝试将布尔字段设置为 false,因为它们不在参数中,但它们不会改变,在我提供的代码中,我希望价格为 5,因为我尚未设置任何其他成分,所以方法 price() 应该只返回我设置的基本价格 (5) 并且不添加任何其他成分,但这不会发生,因为所有布尔字段都设置为 true 意味着它们将为每个真实值加 1,所以退货价格为 9。 问这个问题可能真的很愚蠢,但我是一个完全编程的菜鸟,所以如果有人能解释为什么我没有得到我想要的结果,我会很感激。

public class Hamburger {
    private String bun;
    private String meat;
    private double price;
    private boolean letuce;
    private boolean tomato;
    private boolean bacon;
    private boolean sauce;

    public Hamburger(String bun, String meat) {
        this.bun = bun;
        this.meat = meat;
        this.price = 5;
        this.letuce = false;
        this.tomato = false;
        this.bacon = false;
        this.sauce = false;
    }

    public double price() {

        if(letuce = true)
            price+=1;
        if(tomato = true)
            price+=1;
        if(bacon = true)
            price+=1;
        if(sauce = true)
            price+=1;

        return price;           
    }

    public void setLetuce(boolean letuce) {
        this.letuce = letuce;
    }
    public void setTomato(boolean tomato) {
        this.tomato = tomato;
    }
    public void setBacon(boolean bacon) {
        this.bacon = bacon;
    }
    public void setSauce(boolean sauce) {
        this.sauce = sauce;
    }
}

我希望输出为 5,但输出为 9

【问题讨论】:

  • 您使用赋值运算符= 而不是相等运算符==。分配给true 的结果是true。因此,您的每个 if 检查始终检查 if (true) 并转到相应的 if 分支。
  • 欢迎使用 SO!!,请阅读minimal reproducible example,提供代码执行时的错误堆栈跟踪
  • 考虑使用List<Ingredient> ingredients,其中每种成分都有描述和价格。提供添加/删除成分的方法。 (也许一个汉堡包带有一个默认的成分列表。)然后价格 = basePrice + price of each ingredient。这消除了对if 块的需求(随着时间的推移会增长),并且可以添加新的Ingredient(洋葱)而无需更改Hamburger

标签: java


【解决方案1】:

在您的 if 检查中,您使用 = 而不是 ==。 单个 = 是一个赋值,一个赋值返回赋值,在这种情况下 true 这就是为什么你的代码返回 9 而不是 5 这将按您的预期工作:

public double price() {

    if(letuce == true)
        price+=1;
    if(tomato == true)
        price+=1;
    if(bacon == true)
        price+=1;
    if(sauce == true)
        price+=1;

    return price;           
}

【讨论】:

  • 非常感谢您的快速回复,完全忘记了这个细节。
【解决方案2】:
letuce = true

是一个赋值,将 letuce 的值更改为 true,并且其本身的值为 true

【讨论】:

  • 天哪,我不敢相信是这样,非常感谢您的快速回复。
猜你喜欢
  • 2012-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 2013-05-23
  • 2018-08-02
相关资源
最近更新 更多