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

时间:2015-04-23 15:18:22

标签: 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:\用户\用户1 \文件\的NetBeansProjects \ WordCounter 它被命名为 superfish 并包含以下词语:

超 超 新鲜 超 鱼 晚餐 烦恼 sooper foosh 超 超 超

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

*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*

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

1 个答案:

答案 0 :(得分:3)

searchCount有两大问题:

  1. 实际上并不算数: - )
  2. 检查扫描仪是否有另一行,但只读取一个单词。
  3. 以下是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;
    }