【发布时间】:2012-01-02 19:33:09
【问题描述】:
我有一个问题,如何更改给定类的布尔值,以便一旦再次遇到它,它就具有上次设置的值。这是我的课
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。怎么可能
【问题讨论】:
-
所以你需要它在应用程序的运行之间持久化吗?或者当应用程序运行时?
-
请使用
if (owned)和(!owned),注意在这种情况下执行与!owned相反的测试是多余的,如果不是!owned,它将始终是owned。 -
无论您遇到什么问题,都与
Sandwitch类中的布尔值无关。如果您要单独测试该功能,您会发现设置和读取它可以正常工作。你正在做一些你没有发布的代码,将owned设置为false -
你是不是把卖的三明治和没卖的混在一起,随便挑一个卖,看看有没有卖?看起来你没有正确设计你的三明治店。
-
有没有可能您使用的不是同一个
Sandwich实例而是一个新实例?