[英]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.