为什么不将布尔值设置为true呢?

时间:2019-10-12 20:26:52

标签: java methods boolean

我在一个Java类中有多个全局布尔值,并且由于我不想一遍又一遍地复制和粘贴方法,因此我在下面制作了该方法。问题在于,当我输入“ y”时,应该使参数中的变量为true,但每次检查变量时,即使价格按应有的方式运行,它仍然为false。

我尝试重新整理订单,以查看它是否有做(没有做)。我应该为每个变量创建一个方法吗?

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;
   }
}

(继续) 因此,我检查了“ Java是“按引用传递”还是“按值传递”?”问题,并得出结论:“哦,所以我需要做一些吸气和装气,问题就解决了!”我肯定做错了,因为我收到了错误消息“布尔不能被取消引用”,所以它甚至不允许我编译 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;
}

}

0 个答案:

没有答案