I have the problem how to change boolean value of a given class so that once it is encountered again it has the value last set. This is my class
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;
}
}
and place where it is accessed and supposed to change:
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");
}
}
Problem is that although a given sandwich was bought in the past its owned value is set to false each time I try to run this code. I need for the sandwich to record changed value of owned so that next time I run the condition will be owned == true. How can it
There seems to be a flaw in your design. You need to create a relationship between the Worker and the sandwish type.
What you can do is simply implement a List of purchased sandwish types in the worker class and compare against it whenever a worker purchases a sandwish.
Or if you want, you can have a hashmap of all sandwish types with a boolean value that indicates whether the type has already been purchased or not.