存储布尔值

时间:2012-01-02 19:33:10

标签: java boolean

我遇到了如何更改给定类的布尔值的问题,以便在再次遇到它时,它具有最后设置的值。这是我的班级

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。它怎么可能

3 个答案:

答案 0 :(得分:3)

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

你可以做的只是在工人阶级实施购买的sandwish类型列表,并在工人购买sandwish时与之进行比较。

或者如果你愿意,你可以拥有一个所有sandwish类型的hashmap,其布尔值表示该类型是否已被购买。

答案 1 :(得分:2)

您创建了get和set例程,然后没有使用它们。我会将代码更改为此。

    public void purchase(Sandwich s){
            String type = s.getType();
            if (!(s.getO())){
                if (money <= 0){ 
                    System.out.println("Worker " + this.name + " can not buy " + type + " sandwich, cuz he doesn't have eno

ugh money");
                } else {
                    System.out.println("Worker " + this.name + " can buy " + type + " sandwich");
                    this.money = money;
                    s.setO(true);
                }
            } else {
                System.out.println("Worker " + this.name + " can not buy " + type + " sandwich cuz it was bought");
                System.out.println("Test");
            }
     }

答案 2 :(得分:1)

只需删除

boolean owned = s.owned;

并使用s.getO()

owned

e.g。

if (owned == false){ 

可以

if (!s.getO()){

并使用setter方法s.setO(true/false)进行更改。

e.g。

owned = true;
s.owned = owned;

可以替换为

s.setO(true);