我希望能够从字符串的list
或array
中调用随机字符串。我想要这样做的原因是能够编造一个故事,或者每次都不同的一段文字。到目前为止,我完成的方式是:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Story {
Random myRandom = new Random();
int index = myRandom.nextInt(10);
public static void main(String[] args) {
List<String> adjective = new ArrayList<String>();
adjective.add("efficacious");
adjective.add("propitious");
adjective.add("trenchant");
adjective.add("arcadian");
adjective.add("effulgent");
Story obj = new Story();
System.out.println("This is going to be one " + obj.getRandAdjective(adjective) + " story.");
}
public String getRandAdjective(List<String> adjective) {
int index = myRandom.nextInt(adjective.size());
return adjective.get(index);
}
}
牢记,有什么更有效的方法来构造此结构
还会添加
lists
吗?是否可以将代码的结构缩短到
obj.getRandAdjective(adjective)
版本写在故事(主要是为了提高可读性)?
最佳答案
这是一种概括您对语音各个部分所做的一种方法。我将所有类放在一起以使其易于粘贴。您应该将这些单独的公共课程设为公开。
package com.ggl.testing;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public enum PartsOfSpeech {
ADJECTIVE, ADVERB, ARTICLE, CONJUNCTION, INTERJECTION, NOUN,
PREPOSITION, PRONOUN, VERB
}
class Word {
private final PartsOfSpeech partOfSpeech;
private final String word;
public Word(PartsOfSpeech partOfSpeech, String word) {
this.partOfSpeech = partOfSpeech;
this.word = word;
}
public PartsOfSpeech getPartOfSpeech() {
return partOfSpeech;
}
public String getWord() {
return word;
}
}
class Sentence {
private List<Word> words;
private Random random;
public Sentence() {
this.words = createWordList();
this.random = new Random();
}
private List<Word> createWordList() {
List<Word> words = new ArrayList<Word>();
words.add(new Word(PartsOfSpeech.VERB, "run"));
// add the rest of the words here
return words;
}
public Word getWord(PartsOfSpeech partsOfSpeech) {
List<Word> subList = getSubList(partsOfSpeech);
int index = random.nextInt(subList.size());
return subList.get(index);
}
private List<Word> getSubList(PartsOfSpeech partsOfSpeech) {
List<Word> subList = new ArrayList<Word>();
for (Word word : words) {
if (word.getPartOfSpeech() == partsOfSpeech) {
subList.add(word);
}
}
return subList;
}
}