为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉丁的传说 2022-09-28 15:39:45
因此,我想扫描一个文本文件,并找出我的数组中的单词在该文本文件中的使用次数。使用我的代码,我只能找出在文本文件中找到数组中位置为零的单词的次数。我想要数组中所有单词的总数。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的数量在文本文件中说明)
查看完整描述

2 回答

?
慕尼黑8549860

TA贡献1818条经验 获得超11个赞

扫描文件中的行,然后扫描 匹配项...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++;

            }

        }

    }

}


查看完整回答
反对 回复 2022-09-28
?
猛跑小猪

TA贡献1858条经验 获得超8个赞

这里发生的事情是:在第一个循环中,到达文件的末尾,您只得到“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);


查看完整回答
反对 回复 2022-09-28
  • 2 回答
  • 0 关注
  • 97 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号