Ariver
Ariver

Reputation: 33

Searching and counting a specific word in a text file Java

I've been trying to write a program that reads from a text file, searches for a word, and counts how many instances of that word is in the file.

This would be a sample output:

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

EDIT

My Data file is located in C:\Users\User1\Documents\NetBeansProjects\WordCounter it's named superfish and contains the words:

super super fresh super fish supper fash sooper foosh Super sUPer SUPer

This is the output I get after entering my inputs

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

This is the code that I have written so far, the main issue is that count returns 0 whenever it is run.

I've searched for solutions everywhere and I just can't understand what I'm doing wrong.

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;
    }   
}

Upvotes: 1

Views: 5480

Answers (1)

Mureinik
Mureinik

Reputation: 311143

searchCount has two big problems:

  1. It doesn't actually count :-)
  2. It checks if the scanner has another line, but reads only a single word.

Here's a revised version of searchCount which fixes both issues:

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;
}

Upvotes: 3

Related Questions