【问题标题】:How to populate array with text from a file using Scanner and then randomly select the text from the array?如何使用扫描仪用文件中的文本填充数组,然后从数组中随机选择文本?
【发布时间】:2018-05-08 20:58:35
【问题描述】:

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

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("//s"); 只是将最后一部电影分配给数组,因此数组中只有一个元素。相反,您需要读取每一行并将其分配给数组中的一个条目

标签: java arrays file


【解决方案1】:

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("//");

【讨论】:

  • 赞成,因为我喜欢这个答案,并且会在其他情况下记住这一点
【解决方案2】:

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-loop,或者您可以使用ArrayList,这是一种动态数组

【讨论】:

  • 非常感谢,我以为 //s 会得到所有的电影,但我错了
猜你喜欢
  • 2015-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多