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;
}
我知道您只能在初始化数组时创建数组常量,但是有没有办法制作一个数组实例变量,然后创建一个具有自己的常量的构造函数?
有两种方法可以将数组实例化为常量数组:
String[] subjects = {"Cat", "Dog", "Joe", "Teacher", "Policeman", "Doctor", "Dick"};
或:
String[] subjects;
subjects = new String[] {"Cat", "Dog", "Joe", "Teacher", "Policeman", "Doctor", "Dick"};
在构造函数中,需要使用后者(请注意new String[]
部分(。