2
public class Sentencegenerator {
private String[] subjects;
private String[] verbs; 
private String[] directObjects;

public Sentencegenerator(){
    subjects = {"Cat", "Dog", "Joe", "Teacher", "Policeman", "Doctor", "Dick"};
    verbs = {"eats", "reads", "cums", "farts", "poops", "stabs", "cries"};
    directObjects = {"book", "sticker", "fish", "man", "chiwawa", "marker", "cheese"};
}

public Sentencegenerator(String[] mySubjects, String[] myVerbs, String[]    myDirectObjects){
    subjects = mySubjects;
    verbs = myVerbs;
    directObjects = myDirectObjects;
}

我知道你只能在初始化数组时创建数组常量,但是有没有办法我可以创建一个数组实例变量,然后创建一个拥有自己常量的构造函数?

4

1 回答 1

4

将数组实例化为常量数组有两种方法:

String[] subjects = {"Cat", "Dog", "Joe", "Teacher", "Policeman", "Doctor", "Dick"};

或者:

String[] subjects;
subjects = new String[] {"Cat", "Dog", "Joe", "Teacher", "Policeman", "Doctor", "Dick"};

在您的构造函数中,您需要使用后者(注意new String[]部分)。

于 2013-06-26T21:44:07.833 回答