java - 搜索和计算文本文件 Java 中的特定单词

标签 java file count word

我一直在尝试编写一个程序来读取文本文件、搜索单词并计算该单词在文件中出现的次数。

这将是一个示例输出:

*Enter the name of the text file:
input.dat
Enter the word you're searching for in text file:
that
The word "that" appeared 3 times in the file input.dat*

编辑

我的数据文件位于 C:\Users\User1\Documents\NetBeansProjects\WordCounter 它被命名为 superfish 并包含以下文字:

super 棒 极好的 新鲜的 极好的 鱼 晚餐 时尚 傻瓜 嘘 极好的 极好的 super

这是我输入输入后得到的输出

*运行: 输入文本文件的名称: super 鱼.txt 在文本文件中输入您要搜索的词: 极好的 “super”一词在文件 superfish.txt* 中出现了 0 次*

这是我到目前为止编写的代码,主要问题是每次运行时 count 都会返回 0。

我到处寻找解决方案,但我就是不明白我做错了什么。

import java.util.Scanner;
import java.io.*;

public class WordCounter 
{
    public static void main(String[] args) throws IOException
    {
       Scanner keyboard = new Scanner(System.in);

       System.out.println("Enter the name of the text file:");
       String name = keyboard.nextLine();
       File file = new File(name);

       System.out.println("Enter the word you are searching for in the text file:");
       String word = keyboard.nextLine();

       try
       {
           System.out.println("The word \""+word+"\" appeared "+ searchCount(file,word) +  " times in the file "+ file); 
       }    
       catch (IOException e) 
       {
            System.out.println(e.getMessage());
       }


    }

    public static int searchCount(File fileA, String fileWord) throws FileNotFoundException
    {
        int count = 0;
        Scanner scanner = new Scanner(fileA);

        while (scanner.hasNextLine())
        {
            String nextWord = scanner.next();
            System.out.println(nextWord);
            if (nextWord.equalsIgnoreCase(fileWord))
            count++;

        }
        //End While 
        return count;
    }   
}

最佳答案

searchCount 有两个大问题:

  1. 它实际上不算数:-)
  2. 它检查扫描仪是否有另一行,但只读取一个单词。

这是修复这两个问题的 searchCount 的修订版:

public static int searchCount(File fileA, String fileWord) throws FileNotFoundException
{
    int count = 0;
    fileWord = fileWord.trim();
    Scanner scanner = new Scanner(fileA);

    while (scanner.hasNext()) // Fix issue #2
    {
        String nextWord = scanner.next().trim();
        if (nextWord.equals(fileWord)) { // Fix issue #1
            ++count; 
        }
    }
    //End While 
    return count;
}

关于java - 搜索和计算文本文件 Java 中的特定单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29827718/

相关文章:

file - 如何获取文件的当前位置

ruby - 异步读取 EventMachine 中的文件

Mysql - 如何最大程度地计算表中每天的 Id?

MySql 计算相同的值

java - 应用程序未加载 Music LibGDX

Java:使用for循环用特定范围内的随机整数填充数组

java - 从 application.yml 读取属性时忽略 Spring 配置文件

c++ - 文件大小比应有的大,添加了额外的新行

PHP & MySQL : Count and order most popular values in an array and then print

java - 是否有可能使 IntelliJ 显示提示更加稳健?