简体   繁体   English

如何打印包含另一个类的字符串的数组?

[英]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? 我将如何使用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("");

    }

}

Return the QuestionArray from QuestionDatabase() : QuestionDatabase()返回QuestionArray

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

 }

}

There are a couple ways of doing this. 有两种方法可以做到这一点。 Probably the best way is to create a "getter" method in your questions class. 最好的方法可能是在问题类中创建一个“ getter”方法。 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. 在您的问题课上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM