1

所以我想扫描一个文本文件并找出我的数组中的单词在该文本文件中使用的总次数。

使用我的代码,我只能找出在我的数组中位置为零的单词在文本文件中找到的次数。我想要数组中所有单词的总数。

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 的数量在文本文件中说明)

4

2 回答 2

3

扫描文件中的行,然后扫描arr匹配项...

try (Scanner scan = new Scanner(file)) {
    while (scan.hasNext()) {
        String next = scan.next()
        for(int i = 0; i<arr.length; i++){
            if (next.equals(arr[i])){
              wordCount++;
            }
        }
    }
}
于 2019-04-09T02:04:08.083 回答
0

这里发生的事情是:在第一个循环中,到达文件末尾,你只得到'hello'的计数。您可以在每个循环的结尾/开头重新调整指向文件开头的指针。


String[] arr = {"hello", "test", "example"};
File file = new File(example.txt);
int wordCount = 0;

for(int i = 0; i<arr.length; i++){
   Scanner scan = new Scanner(file);
   while (scan.hasNext()) {
   if (scan.next().equals(arr[i])){
          wordCount++;
        }
 }
}
System.out.println(wordCount);
于 2019-04-09T02:03:20.227 回答