[英]Java - I need to use a variable boolean inside the main method, initialized outside but within the same class
The boolean has to be outside the main method so other methods can manipulate it. 布尔值必须在main方法之外,以便其他方法可以对其进行操作。 I've searched everywhere and cannot find a suitable answer because all I stumble upon are solutions for booleans as methods. 我到处搜索,找不到合适的答案,因为我偶然发现的只是布尔方法的解决方案。 It has to be a simple boolean and it cannot be static. 它必须是一个简单的布尔值,并且不能是静态的。 Don't have much time, so any help would be great. 没有太多的时间,所以任何帮助都会很棒。 Thanks. 谢谢。
public class myClass {
private int[][] holdsStuff;
private boolean isNeeded;
public setFalse (){
}
public setTrue () {
}
public static void main(String[] args) {
//call methods to change isNeeded
//require isNeeded to prevent invalid changes being made to holdsStuff
}
}
If class member isNeeded
is not static, then it must belong to an instance of myclass
, you can create a new instance and manipulate this instance: 如果类成员isNeeded
不是静态的,则它必须属于myclass
的实例,您可以创建一个新实例并操纵该实例:
public class myClass {
private int[][] holdsStuff;
private boolean isNeeded;
public void setFalse (){
isNeeded = false;
}
public void setTrue () {
isNeeded = true;
}
public static void main(String[] args) {
myClass mc = new myClass();
myClass.setFalse();
}
}
public class myClass {
private int[][] holdsStuff;
private boolean isNeeded;
public void setFalse (){
isNeeded =false;
}
public void setTrue () {
isNeeded = true;
}
public static void main(String[] args) {
myClass myclass = new myClass();
myclass.setFalse();
myclass.setTrue();
//call methods to change isNeeded
//require isNeeded to prevent invalid changes being made to holdsStuff
}
}
since main is static either use static keyward or make an instance of the same class. 由于main是静态的,所以请使用静态keyward或创建同一类的实例。 use static key the following: 使用静态密钥如下:
public class myClass {
private int[][] holdsStuff; // make this static if you are also this inside main
private static boolean isNeeded;
public static setFalse (){
}
public static setTrue () {
}
public static void main(String[] args) {
//call methods to change isNeeded
//require isNeeded to prevent invalid changes being made to holdsStuff
}
}
You want to use isNeeded in other methods and in main method which is static and static methods just deal with static data read this . 您想在其他方法和主要方法中使用isNeeded ,这是静态方法,而静态方法只是处理静态数据, 请阅读此内容 。 so what you want to do is make instance of this class to call isNeeded in main method 所以您要做的是在主方法中使此类的实例调用isNeeded
public static void main(String[] args) {
myClass myclass = new myClass();
boolean isNeeded = myclass.isNeeded;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.