繁体   English   中英

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

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

我将如何使用println打印一个包含另一个类中的字符串的数组? 我的意思是一个例子:

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

    }

}

在另一堂课中,我想像这样从那里抓住一个问题:

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

    }

}

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;

}

然后像这样打印:

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

 }

}

有两种方法可以做到这一点。 最好的方法可能是在问题类中创建一个“ getter”方法。 该方法将简单地返回您创建的数组,并且如果将该方法公开,则可以从其他类访问它而无需更改数组的值。 例如:

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

在您的问题课上。

暂无
暂无

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

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