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],但这不起作用。还有其他建议吗?
谢谢。
最佳答案
要每次获取第一个单词,您可以将 String randomWord = Words.get(rand.nextInt(words.size()));
替换为:
String randomWord = words.get(0);
关于java - 关于仅从方法调用返回相同值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61114615/