首页 > 解决方案 > 如何使用 Scanner 使用文件中的文本填充数组,然后从数组中随机选择文本?

问题描述

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

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

标签: javaarraysfile

解决方案


movieList = Line.Split("//") 这一行总是用文件中的最后一行覆盖movielist:Alladin

而是像下面这样写:

ArrayList<String> movieList = new ArrayList<>();
while (fileScanner.hasNextLine()) {
    String line = fileScanner.nextLine();
    movieList.add(line);
}

重要的是要注意,如果所有电影名称都在同一行并且在它们的名称之间没有像这样的白色香料,那么您的原始方法将会成功:

KangarooJack Superman ShawshankRedemption Aladdin

循环也没有必要。所以它可以这样写:

String[] movieList = {};
String line = fileScanner.nextLine();
movieList = line.split("//s");

如果你想变得非常狂野......

String[] movieList = fileScanner.nextLine().split("//");

推荐阅读