GotRiff
GotRiff

Reputation: 87

How do I print an array that holds a string from another class?

How would I go about printing an array that holds a string that is in another class using println? An example of what I mean is:

public class questions{

    public void QuestionDatabase(){

        String[] QuestionArray;
        QuestionArray = new String[2];

        QuestionArray[0] = ("What is a dog?");
        QuestionArray[1] = ("How many types of dogs are there?");

    }

}

In this other class, I want to grab a question from there like so:

public class quiz{

    public static void main (String[] args){

       //Here is where I want to grab QuestionArray[0] and print to the screen.
        System.out.println("");

    }

}

Upvotes: 0

Views: 94

Answers (2)

jhobbie
jhobbie

Reputation: 1016

There are a couple ways of doing this. Probably the best way is to create a "getter" method in your questions class. This method will simply return the array you have created, and if you make that method public, you can access it from other classes without changing the value of your array. For example:

public String[] getQuestionArray(){
    return QuestionArray;
}

in your question class.

Upvotes: 0

betteroutthanin
betteroutthanin

Reputation: 7576

Return the QuestionArray from QuestionDatabase():

public String[] QuestionDatabase(){

    String[] QuestionArray;
    QuestionArray = new String[2];

    QuestionArray[0] = ("What is a dog?");
    QuestionArray[1] = ("How many types of dogs are there?");

    return QuestionArray;

}

Then print like this:

public class quiz{

public static void main (String[] args){

   //Here is where I want to grab QuestionArray[0] and print to the screen.
    System.out.println(new questions().QuestionDatabase()[0]);

 }

}

Upvotes: 2

Related Questions