簡體   English   中英

存儲布爾值

[英]storing boolean value

我有一個問題,如何更改給定類的布爾值,以便一旦再次遇到它,它的值將被最后設置。 這是我的課

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類型的哈希圖,並帶有一個布爾值,指示該類型是否已購買。

您創建了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");
            }
     }

只需刪除

boolean owned = s.owned;

並使用s.getO() ,其中您owned

例如

if (owned == false){ 

if (!s.getO()){

並使用設置方法s.setO(true/false)進行更改。

例如

owned = true;
s.owned = owned;

可以替換為

s.setO(true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM