所以我想扫描一个文本文件并找出我的数组中的单词在该文本文件中使用的总次数。
使用我的代码,我只能找出在我的数组中位置为零的单词在文本文件中找到的次数。我想要数组中所有单词的总数。
String[] arr = {"hello", "test", "example"};
File file = new File(example.txt);
int wordCount = 0;
Scanner scan = new Scanner(file);
for(int i = 0; i<arr.length; i++){
while (scan.hasNext()) {
if (scan.next().equals(arr[i])){
wordCount++;
}
}
}
System.out.println(wordCount);
example.txt 如下:
hello hello hi okay test hello example test
this is a test hello example
为此,我想要的结果是 wordCount = 9
相反,我上面的代码的 wordCount 等于 4(hello 的数量在文本文件中说明)