我有一个问题,如何更改给定类的布尔值,以便一旦再次遇到它,它的值将被最后设置。这是我的课

public class Sandwich {
    private String type;
    private double price;
    private String ing;
    public boolean owned;

    Sandwich (String t, double p, boolean o){
        type = t;
        price = p;
        owned = o;
    }

    public boolean getO(){
        return this.owned;
    }

    public void setO(boolean o){
        this.owned = o;
    }

    public String getType(){
        return this.type;
    }
}


以及访问它并应该更改的地方:

public void purchase(Sandwich s) {
    boolean owned = s.owned;

    //I tried also with accessor and mutator here but then changed to public
    String type = s.getType();
    if (owned == false) {
        if (money <= 0){
            System.out.println("Worker " + this.name + " can not buy " + type + " sandwich, cuz he doesn't have enough money");
        } else {
            System.out.println("Worker " + this.name + " can buy " + type + " sandwich");
            this.money = money;
            owned = true;

            //this is the place where it is supposed to change value to true (sandwich was bought and has owner now
            s.owned = owned;
        }
    } else if (owned == true) {
        System.out.println("Worker " + this.name + " can not buy " + type + " sandwich cuz it was bought");
        System.out.println("Test");
    }
}


问题是,尽管过去购买了给定的三明治,但每次我尝试运行此代码时,其自有值都设置为false。我需要三明治来记录所拥有的更改的值,以便下次运行该条件时将拥有== true。怎么会

最佳答案

您的设计似乎存在缺陷。您需要在Worker和sandwish类型之间创建关系。

您可以做的就是简单地在worker类中实现已购买的Sandwish类型的列表,并在工人购买Sandwish时将其与之进行比较。

或者,如果需要,您可以拥有所有带有Sandwish类型的哈希图,并带有一个布尔值,指示该类型是否已购买。

关于java - 存储 boolean 值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8704623/

10-11 02:32