英文:
Java Programming - method setting variable to false
问题
我正在进行我的前几堂Java编程课程。有人要求我设计一个将变量设置为false的方法。我该如何编写代码?我已经尝试了下面的代码,但我知道它离正确还很远。
以下是您给出的代码:
public exitHall(Boolean onPremises == false);
为了提供背景信息,问题要求我创建一个名为exitHall的方法,该方法将一个变量设置为false。
任何建议将不胜感激。谢谢
英文:
I am having my first few lessons in Java programming. I have been asked me to design a method that sets a variable to false. How do I go about writing the code? I've given an attempt below but I know it is far from correct.
Code below
public exitHall(Boolean onPremises == false);
For context, the question asks me to create an exitHall method, which sets a variable to false.
Any suggestions would be much appreciated. Thank you
答案1
得分: 1
你可以有一个特定的方法来将变量设置为false,就像这样:
public void exitHall(){
this.onPremises=false;
}
然后你可以有一个类似这样的getter方法:
public boolean isOnPremises(){
return this.onPremises();
}
请记住,你确实需要像这样定义变量onPremises:
public class BanquetHall{
private boolean onPremises;
//获取器和设置器
}
我们将其设置为private,因为通常情况下,我们不希望其他任何类在未访问setter方法的情况下修改它。这确保了代码完整性。
英文:
You can have a specific method for setting the variable to false like so:
public void exitHall(){
this.onPremises=false;
}
Then you can have a getter method like so:
public boolean isOnPremises(){
return this.onPremises();
}
Keep in mind you do need to define the variable onPremises like so:
public class BanquetHall{
private boolean onPremises;
//Getters and setters
}
We set it to private, because normally we don't want any other class to modify it without accessing the setter method. This ensures code integrity.
答案2
得分: 0
如果您有一个布尔变量,例如:
boolean onPremises;
Setter 和 Getter 方法:
public boolean isOnPremises() {return this.onPremises;}
public void setOnPremises(boolean onPremises) {this.onPremises = onPremises;}
如果您想要在方法中设置变量的值,那么可以使用这个方式:
public void exitHall(boolean onPremises) {
this.onPremises = onPremises;
// 在这个方法中可能需要额外的代码
}
英文:
If you have a boolean variable, for example :
boolean onPremises;
Setter and Getters :
public boolean isOnPremises(){return this.onPremises;}
public void setOnPremises(boolean onPremises){this.onPremises = onPremises;}
If you want to set a variable value in a method then use this :
public void exitHall(boolean onPremises) {
this.onPremises = onPremises;
//any additional code required in this method
}
答案3
得分: -1
Boolean onPremises; //默认值为false
public void setOnPremises(Boolean status){
this.onPremises = status;
} //此方法将帮助您更改布尔状态
public boolean getOnPremises(){
System.out.println(onPremises);
return onPremises;
} //此方法将帮助您获取当前的布尔状态
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论