0

I am making a simple Java program which should read a txt file and count the number of times a specific word has been mentioned. This is what I have below, it compiles and runs fine but keeps returning 0 for the answer when it should run well into the thousands...

On this occasion I am wondering how many times "am via" were mentioned in this file...

/*AUTHOR Yun Lee
Finding out the number of tweets per day*/

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

class tweetnumber
{

public static void main(String args[])
{
    try
    {

        FileInputStream fstream = new FileInputStream("tacobell.23jan2012.txt");
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;

        int counter1 = 0;
        String s = "am via";

        while ((strLine = br.readLine()) != null)   
        {
            System.out.println (strLine);
            if (strLine.contains(s))
            {
                counter1++;
            }

        }
        in.close();
        System.out.println("There were " + counter1 + " messages in the AM of this day");
    }

    catch (Exception e)
    {
        System.err.println("Error: " + e.getMessage());
    }

}
}
Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
  • Does the file get printed by your `println` statement? Tried setting a breakpoint and inspecting `strLine` to make sure it contains "am via"? – Blorgbeard Feb 13 '12 at 17:50
  • 1
    should this be tagged as homework ? and by the way, what happens if the string youre looking for appears more than once in a row? – jambriz Feb 13 '12 at 17:56
  • Is `"am via"` supposed to be only a single word? Or are you trying to look for occurrences of the words "am" and "via"? – Louis Wasserman Feb 13 '12 at 18:36

3 Answers3

1

A FileInputStream is supposed to be used for

FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

Because you are trying to read characters, try opening your file differently. You can try:

File f = new File("tacobell.23jan2012.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
simchona
  • 1,878
  • 3
  • 19
  • 18
1

I tested it and it works for the text file being encoded as ANSI. I then tried it on the same file encoded as Unicode with one additional "fishy" character like: ♣, and there it went: 0 So check your input file or the way you read it.

Try this post here.

Community
  • 1
  • 1
Iulius Curt
  • 4,984
  • 4
  • 31
  • 55
0

DataInputStream might not be converting your file from bytes to characters properly. Try removing it, and passing the FileInputStream to the InputStreamReader constructor.

jbowes
  • 4,062
  • 22
  • 38