mercredi 8 avril 2020

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;
}

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 and adding the first instance of this to the list, then call randomWord[0], but that didn't work. Any other suggestions?

Thanks.




Aucun commentaire:

Enregistrer un commentaire