Java编程-方法设置变量为false

问题描述

我正在学习Java编程的前几节课。我被要求设计一种将变量设置为false的方法。我该如何编写代码?我在下面进行了尝试,但我知道这是不正确的。 下面的代码

public exitHall(Boolean onPremises == false);

对于上下文,问题要求我创建一个exitHall方法,该方法将变量设置为false。

任何建议将不胜感激。谢谢

解决方法

您可以使用一种将变量设置为false的特定方法,如下所示:

public void exitHall(){
    this.onPremises=false;
}

然后您可以使用如下的getter方法:

public boolean isOnPremises(){
    return this.onPremises();
}

请记住,您确实需要像这样定义变量 onPremises

public class BanquetHall{
    private boolean onPremises;
    //Getters and setters
}

我们将其设置为私有,因为通常我们不希望任何其他类在不访问setter方法的情况下对其进行修改。这样可以确保代码完整性

,

如果您具有布尔变量,例如:

boolean onPremises;

Setter and Getters:

public boolean isOnPremises(){return this.onPremises;}

public void setOnPremises(boolean onPremises){this.onPremises = onPremises;}

如果要在方法中设置变量值,请使用以下方法:

public void exitHall(boolean onPremises) {
    this.onPremises = onPremises;
    //any additional code required in this method
}
,
   
        Boolean onPremises; //default value false
    
    
    public void setOnPremises(Boolean status){
          this.onPremises = status;
         
      }  //this method will help you to change the boolean status
    
     public boolean getOnPremises(){
          System.out.println(onPremises);
          return onPremises;
        
      }  //this method will help to get the current boolean status