Nonanol_C9H20O
Nonanol_C9H20O

Reputation: 15

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

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,

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. So I'm guessing the public static in "public static void main(String args[]){" is the thing messing it up. What should I do?

Upvotes: 1

Views: 338

Answers (1)

Nathan Hughes
Nathan Hughes

Reputation: 96434

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.

Upvotes: 2

Related Questions