Java 如何使用扫描仪从文件中填充数组文本,然后从数组中随机选择文本?

Java 如何使用扫描仪从文件中填充数组文本,然后从数组中随机选择文本?,java,arrays,file,Java,Arrays,File,我有一个包含电影列表的文本文件: Kangaroo Jack Superman Shawshank Redemption Aladdin 我要做的是将所有这些胶片传递到一个数组中,然后从数组中随机选择一个胶片。然而,它似乎总是选择“阿拉丁”,我不知道我做错了什么?如何从阵列中随机选择胶片 public static void main(String[] args) throws FileNotFoundException { String[] movieList = {};

我有一个包含电影列表的文本文件:

Kangaroo Jack
Superman
Shawshank Redemption
Aladdin
我要做的是将所有这些胶片传递到一个数组中,然后从数组中随机选择一个胶片。然而,它似乎总是选择“阿拉丁”,我不知道我做错了什么?如何从阵列中随机选择胶片

public static void main(String[] args) throws FileNotFoundException {

    String[] movieList = {};
    File file = new File("xxx\\listofmovies.txt");
    Scanner fileScanner = new Scanner(file);
    Scanner scanner = new Scanner(System.in);
    Random random = new Random();

    while (fileScanner.hasNextLine()) {
        String line = fileScanner.nextLine();
        // Reads the whole file
        movieList = line.split("//s");
        //splits the string by white space characters meaning we will get the full word(s) per line
    }

    boolean weArePlaying = true;
    while (playing) {

        char[] randomWordToGuess = movieList[random.nextInt(movieList.length)].toLowerCase().toCharArray();
        int wordLength = randomWordToGuess.length;
        char[] playerGuess = new char[wordLength];
        boolean wordCompleted = false;
...
}
movieList=Line.Split// 这一行总是用文件中的最后一行:Alladin覆盖movielist

不如像下面这样写:

ArrayList<String> movieList = new ArrayList<>();
while (fileScanner.hasNextLine()) {
    String line = fileScanner.nextLine();
    movieList.add(line);
}
如果你想变得狂野

String[] movieList = fileScanner.nextLine().split("//");
movieList=line.split//s;只将最后一部电影分配给数组,因此数组中只有一个元素。相反,您需要读取每一行并将其分配给数组中的一个条目

也许更像

String[] movieList = new String[4];
File file = new File("xxx\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
Scanner scanner = new Scanner(System.in);
Random random = new Random();

int index = 0;
while (fileScanner.hasNextLine()) {
    String line = fileScanner.nextLine();
    movieList[index] = line;
    index++;
}
这假设文件中只有4行,如果没有,那么您将有IndexOutOfBoundsException


你可以用很多方法来预防这种情况。您可以将预期的行数作为文件的第一行,然后根据该行创建数组,也可以在数组已满时退出while循环,或者使用ArrayList,这是一种动态数组

movieList=line.split//s;只将最后一部电影分配给数组,因此数组中只有一个元素。相反,你需要阅读每一行并将其分配到数组中的一个条目谢谢,我以为//s会得到所有的电影,但我被错误地选了,因为我喜欢这个答案,在另一个场景中会记住这一点
String[] movieList = new String[4];
File file = new File("xxx\\listofmovies.txt");
Scanner fileScanner = new Scanner(file);
Scanner scanner = new Scanner(System.in);
Random random = new Random();

int index = 0;
while (fileScanner.hasNextLine()) {
    String line = fileScanner.nextLine();
    movieList[index] = line;
    index++;
}