gpt4 book ai didi

java - 存储 boolean 值

转载 作者:行者123 更新时间:2023-12-01 16:36:15 36 4
gpt4 key购买 nike

我遇到的问题是如何更改给定类的 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。怎么可能

最佳答案

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

您可以做的只是在 worker 类(Class)中实现一个购买的三明治类型列表,并在 worker 购买三明治时与它进行比较。

或者,如果您愿意,您可以拥有所有三明治类型的 HashMap ,其中包含一个 boolean 值,指示该类型是否已被购买。

关于java - 存储 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8704623/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com