我有問題如何更改給定類的布爾值,以便一旦它再次遇到它有最後一次設置的值。這是我的課存儲布爾值
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");
}
}
問題是,雖然給定的三明治是在過去購買了國有值設置爲每次假我嘗試運行此代碼。我需要三明治來記錄擁有的改變後的價值,以便下次我運行該條件時將擁有== true。它怎麼可能
所以你需要它堅持之間的應用程序的運行?或者當應用程序正在運行? – Joe 2012-01-02 19:37:18
請使用'if(擁有)'和'(擁有)',注意在這種情況下,執行與'!owned'測試相反的操作是多餘的,如果它不是'!owned',它將總是'擁有' 。 – 2012-01-02 19:38:08
無論你遇到什麼問題,它與'Sandwitch'類中的布爾值無關。如果您要自行測試功能,您會發現設置它並閱讀它可以正常工作。你在代碼中做了一些你沒有發佈的代碼,將'擁有'設置爲'false' – 2012-01-02 19:38:19