因此,我想扫描一个文本文件,并找出我的数组中的单词在该文本文件中的使用次数。
使用我的代码,我只能找出在文本文件中找到数组中位置为零的单词的次数。我想要数组中所有单词的总数。
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);
示例.txt如下所示:
hello hello hi okay test hello example test
this is a test hello example
在那里,我想要的期望结果是字数计数 = 9
相反,我上面的代码的单词计数等于4(hello的数量在文本文件中说明)
慕尼黑8549860
猛跑小猪
相关分类