英文:
Question about only returning the same value from a method call
问题
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;
}
我在许多不同的方法中调用这个chooseWord()方法,我只想每次调用它时返回相同的字符串。目前,它每次从"Wordlist.txt"中返回一个随机单词。我尝试过创建一个ArrayList
英文:
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;
}
I call this method chooseWood() in many different methods and I only want to return the same String every time its called. Currently, it's returning a random word every time its called from the "Wordlist.txt". I tried creating an ArrayList<String> and adding the first instance of this to the list, then call randomWord[0], but that didn't work. Any other suggestions?
Thanks.
答案1
得分: 0
为了每次获得第一个单词,您可以将 String randomWord = words.get(rand.nextInt(words.size()));
替换为:
String randomWord = words.get(0);
英文:
To get the first word every time, you can replace String randomWord = words.get(rand.nextInt(words.size()));
with :
String randomWord = words.get(0);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论