关于只从方法调用中返回相同的值的问题

huangapple go评论65阅读模式
英文:

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,并将第一个实例添加到列表中,然后调用randomWord[0],但那行不通。还有其他建议吗?谢谢。

英文:
    public static String chooseWord() throws IOException {
    String fileName = &quot;Wordlist.txt&quot;;
    File file = new File(fileName);
    FileInputStream fis = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(isr);
    String line;
    List&lt;String&gt; words = new ArrayList&lt;String&gt;();
    while((line = br.readLine()) != null){
        String[] wordsLine = line.split(&quot; &quot;);
        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);

huangapple
  • 本文由 发表于 2020年4月9日 13:38:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/61114615.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定