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

    }

}
GotRiff
  • 87
  • 1
  • 3
  • 9
  • 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. – ovie Jul 23 '14 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. – ajb Jul 23 '14 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. – ajb Jul 23 '14 at 16:58

2 Answers2

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

 }

}
betteroutthanin
  • 7,148
  • 8
  • 29
  • 48
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.

jhobbie
  • 1,016
  • 9
  • 18