0

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("");

    }

}
3
  • just return String[] insteand of void et return QuestionArray. Or put your array in field and use a getter method. By the way class name should begin with an uppercase and variables names should begin with lowercase, that's a standard. Commented Jul 23, 2014 at 16:07
  • Note that in the code you've written, QuestionArray is a local variable that belongs to the QuestionDatabase method. When you call the method, it sets up the array, but when the method is done, the array disappears, along with all the work you did to set it up. The answers explain how to fix this. Commented Jul 23, 2014 at 16:09
  • 1
    @Jarrod You have marked this as a duplicate of the wrong question. This question is about a local variable that shouldn't be local. The question you linked to is about a common problem where programmers try to use toString() on an array and get garbage output like [I@3343c8b3. Voting to reopen. Commented Jul 23, 2014 at 16:58

2 Answers 2

2

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]);

 }

}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.