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