0

I have multiple global booleans in a java class and since I didn't want to copy and paste a method over and over again, I made the method below. problem is that when I enter "y" it's supposed to make the variable in parameter a true, but every time I checked the variable it's still false, even though the price works the way it should.

I tried shuffling the order around to see if it did anything (it didn't). should I just make a method for each variable instead?

public void wants(String b, boolean a){
   while(!b.equalsIgnoreCase("y") && !b.equalsIgnoreCase("n")){
       System.out.println("Please enter y or n");
       b = keyboard.next();
   }
   if(b.equalsIgnoreCase("y")){
        a = true;
        price += 0.5;
   }
   else if(b.equalsIgnoreCase("n")){
        a = false;
   }
}

(Continuation) So I checked out "Is Java 'pass-by-reference' or 'pass-by-value'?" question and came to the conclusion of 'oh, so I need to make some getters and setters and the problem will be solved!' I definitely did something wrong though since I'm getting the error message 'boolean cannot be dereferenced' so it's not even letting me compile which is big oof.

//private vars (project requirement, can't be removed)
private boolean wantsCheese, wantsGuac, wantsCream;

public void takeOrder() {
    System.out.println("Do you want cheese? (Y/N)");
    //was initially wants(keyboard.next(), wantsCheese); for previous method
    wantsCheese.wants(keyboard.next());
}
...
public void wants(String b){
    while(!b.equalsIgnoreCase("y") && !b.equalsIgnoreCase("n")){
       System.out.println("Please enter y or n");
       b = keyboard.next();
   }
   if(b.equalsIgnoreCase("y")){
       setCheese(true);
       price += 0.5;
   }
   else if(b.equalsIgnoreCase("n")){
      setCheese(false);
   }
}
public boolean getCheese(){
   return this.wantsCheese;
}
public void setCheese(boolean wantsCheese){
   this.wantsCheese = wantsCheese;
}
public boolean getGuac(){
   return this.wantsGuac;
}
public void setGuac(boolean wantsGuac){
   this.wantsGuac = wantsGuac;
}
public boolean getCream(){
   return this.wantsCream;
}
public void setCream(boolean wantsCream){
   this.wantsCream = wantsCream;
}

}

McGremlin
  • 1
  • 4
  • You are working with a parameter all the time. Use a local variable instead, then it should work. Like String c = b; above the while loop and then replace b with c everywhere – Patrick Oct 12 '19 at 20:34
  • oof, no bueno. thanks for helping tho – McGremlin Oct 12 '19 at 20:58

0 Answers0