我有一个包含电影列表的文本文件:
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("//")
此行始终用文件中的最后一行覆盖 movielist:Alladin
最好像下面这样写:
ArrayList<String> movieList = new ArrayList<>();
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
movieList.add(line);
}
值得注意的是,如果所有电影名称都在同一行并且名称之间没有白色香料,那么您最初的方法就会成功,如下所示:
袋鼠 jack 超人肖申克的救赎阿拉丁
循环也不是必要的。所以它可以写成这样:
String[] movieList = {};
String line = fileScanner.nextLine();
movieList = line.split("//s");
如果你想变得非常狂野......
String[] movieList = fileScanner.nextLine().split("//");
关于java - 如何使用扫描仪使用文件中的文本填充数组,然后从数组中随机选择文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50242172/