java - 如何使用 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;
...
}
解决方案
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("//");
推荐阅读
- vespa - 'vespa.ai' 中不区分大小写的匹配
- opencart - 如何将 Opencart 从根目录移动到子文件夹
- google-bigquery - 如何使用 BigQueryIO.read 使用 SerializableFunction() 而不是 BigQueryIO.readTableRows()
- javascript - require.context 不会随着图片上传而更新
- angular - 错误:this.scrollableDiv.nativeElement 未定义
- r - Plotly:用动画图表处理缺失值
- javascript - 重新启动时防止视频重新加载
- windows - Jenkins 构建后如何在 Windows 上启动应用程序
- c# - CREATE FILE 在尝试打开或创建物理文件时遇到操作系统错误 5(访问被拒绝。)
- angular - !x 等价于 (x===undefined || x.length===0)