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

时间:2018-05-08 20:58:35

标签: java arrays file

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

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

2 个答案:

答案 0 :(得分:1)

package io.tester; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; public class JavaHttpUrlConnectionReader { public static void main(String[] args) throws Exception { new JavaHttpUrlConnectionReader(); } public JavaHttpUrlConnectionReader() { try { String myUrl = "http://localhost:8080/add?value1=8&value2=4.2"; String myUrl1 = "http://localhost:8080/validate?value=123"; String results = doHttpUrlConnectionAction(myUrl); String results1 = doHttpUrlConnectionAction(myUrl1); System.out.println(results); System.out.println(results1); } 这一行总是用文件中的最后一行覆盖movielist:Alladin

而是像下面这样写:

movieList = Line.Split("//")

重要的是要注意,如果所有的电影名称都在同一条线上并且在它们的名字之间没有白色的香料,那么你的原始方法就会成功:

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

答案 1 :(得分:0)

SELECT * FROM TableA a LEFT JOIN TableB b ON a.col1 = b.col1 OR (a.col1 != b.col1 AND a.col2 = b.col2) 仅将最后一部电影分配给数组,因此数组中只有一个元素。相反,您需要读取每一行并将其分配给数组中的条目。

也许更喜欢......

movieList = line.split("//s");

这假设文件中只有4行,如果没有,那么你将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++; }

你可以通过多种方式防范这种情况。您可以将预期行数作为文件的第一行,然后根据该行创建数组,或者可以在数组已满时退出IndexOutOfBoundsException,或者可以使用while-loop,是一种动态数组