【发布时间】:2020-04-09 05:38:39
【问题描述】:
public static String chooseWord() throws IOException {
String fileName = "Wordlist.txt";
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line;
List<String> words = new ArrayList<String>();
while((line = br.readLine()) != null){
String[] wordsLine = line.split(" ");
for(String word: wordsLine){
words.add(word);
}
}
String randomWord = words.get(rand.nextInt(words.size()));
return randomWord;
}
我在许多不同的方法中调用这个方法chooseWood(),我只想在每次调用它时返回相同的字符串。目前,每次从“Wordlist.txt”中调用它时,它都会返回一个随机单词。我尝试创建一个 ArrayList 并将它的第一个实例添加到列表中,然后调用 randomWord[0],但这不起作用。还有其他建议吗?
谢谢。
【问题讨论】: