使用计数作为字符串的索引如何生成随机单词?

using count as index of string how to generate random words?

我正在编写一个 hangman 程序,我希望 word 文本文件工作正常,能够填充数组列表并从数组列表中生成一个随机单词。但我想做一些新的事情。该程序正在做的事情相当简单直接,它是逐行读取文本文件,每次读取一行时都会增加计数。但我想使用计数值作为文本文件中单词的索引从该文本文件生成一个随机单词。任何人都可以帮助我在哪里可以获得有关此问题的文档?

public class WordReader {


    private static String fileName = "Wordlist.txt";
    int count = 0;

    public WordReader() throws FileNotFoundException {
        File file = new File(fileName);
        try(Scanner sc = new Scanner(new FileInputStream(file))){
            int count=0;
            while(sc.hasNext()){
                sc.next();
                count++;
            }

        }
    }
}

将它们加载到字符串数组列表中,因此首先初始化数组列表

ArrayList<String> dict = new ArrayList()<>;

然后你需要在数组List中添加一行(假设每行一个单词)

dict.add(sc.next);

所有单词都添加到列表后,您需要获取单词长度的随机数

Random rand = new Random();
int choice = rand.nextInt(dict.size());
String wordChoice = dict.get(choice);
String[] words = new string[<Size of array, for example lines count>]

然后在"words"数组中逐行添加单词

using (StreamReader a = new StreamReader("Words.txt")){
    words[i] = a.ReadLine();
}

现在你需要得到一条随机线

Random rnd = new Random();
int random = rnd.next(0,words.Count()-1)
string output = words[random];