[英]How do I load an variable from a java class to a different class
I'm trying to load a String from topicRNG to changeXML. 我正在尝试将一个字符串从topicRNG加载到changeXML。 I've loaded variables between classes before but can't get it to work now.
我之前在类之间加载了变量,但现在无法使其正常工作。
Firstly I have my code where I try to load it. 首先,我在尝试加载代码的地方。 package XMLTest;
包XMLTest;
public class ModifyTTXML {
public static void main(String args[]){
TopicRNG.main();
String something = TopicRNG.topicFinal;
...
And then the code where I try to load it, 然后是我尝试加载的代码
import java.util.Random;
public final class TopicRNG {
public static final void main(String... aArgs){
String lastTopic = "empty";
int lastTopicNumber; //genre ska importeras från GameSetup screenen
Random randomGenerator = new Random();
...
if(GenreDefiner.genre<=1){
System.out.println(topicName[lastTopicNumber]);
topicFinal = topicName[lastTopicNumber]; }
When I loaded the int from GenreDefiner I had it set up like this, 当我从GenreDefiner加载int时,我进行了如下设置:
public class GenreDefiner {
public static int genre = 1;
}
I tried "putting public static String topicFinal" and it gave me an error, when I instead put it outside of the "public static void main(String args[]){}" it worked fine. 我尝试“放入公共静态String topicFinal”,但给了我一个错误,当我将其放在“公共静态void main(String args []){}”之外时,它工作正常。 So I'm guessing the public static in "public static void main(String args[]){" is the thing messing it up.
因此,我猜测“ public static void main(String args []){”中的public static是一件麻烦事。 What should I do?
我该怎么办?
What you should do is pass values as arguments to methods and try to minimize using static variables except as global constants. 您应该做的是将值作为方法的参数传递,并尝试将静态变量(作为全局常量除外)使用到最小。
You can't declare a static variable inside a method, it has to be within the class declaration but outside of any method declaration. 您不能在方法内部声明静态变量,它必须在类声明内,但不能在任何方法声明内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.