在文本文件中搜索和计算特定单词 Java

Searching and counting a specific word in a text file Java

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

这将是一个示例输出:

*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 并包含文字:

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

这是我输入后得到的输出

*run: Enter the name of the text file: superfish.txt Enter the word you are searching for in the text file: super The word "super" appeared 0 times in the file superfish.txt*

这是我到目前为止写的代码,主要问题是 returns 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;
}