猿问

如何查看字符串数组中的单词在文本文件中出现的次数

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


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


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


拉丁的传说
浏览 98回答 2
2回答

慕尼黑8549860

扫描文件中的行,然后扫描 匹配项...arrtry (Scanner scan = new Scanner(file)) {&nbsp; &nbsp; while (scan.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; String next = scan.next()&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 0; i<arr.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (next.equals(arr[i])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wordCount++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

猛跑小猪

这里发生的事情是:在第一个循环中,到达文件的末尾,您只得到“hello”的计数。您可以在每个循环的末尾/开头重新调整指向文件开头的指针。String[] arr = {"hello", "test", "example"};File file = new File(example.txt);int wordCount = 0;for(int i = 0; i<arr.length; i++){&nbsp; &nbsp;Scanner scan = new Scanner(file);&nbsp; &nbsp;while (scan.hasNext()) {&nbsp; &nbsp;if (scan.next().equals(arr[i])){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wordCount++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp;}}System.out.println(wordCount);
随时随地看视频慕课网APP

相关分类

Java
我要回答