PineCone
PineCone

Reputation: 2343

wordCount frequency returns repeated Set in java

I have a method which returns single word as a String. I need to count all those words returned by the method which reads chunk of text. Problem is I am getting the count right but output is wrong. It's repeating. Not quite sure where is things going wrong?

private int totalWords    = 0;
private static Map<String, Integer> wordFrequency = new HashMap<String, Integer>();


public static void findResult(CharacterReader characterReader)
{
    boolean x = true;
    CharBuffer buffer = CharBuffer.allocate(100);
    String str = "";
    try
    {

        while(x)
        {
        char cha = characterReader.getNextChar();
        Set<Character> charSet = new HashSet<Character>();
            charSet.add(',');
            charSet.add('.');
            charSet.add(';');
            charSet.add(':');
            charSet.add('\'');
            charSet.add('~');
            charSet.add('?');
            charSet.add('!');
            charSet.add('%');


            while(cha != ' ' && !charSet.contains(cha))
            {
                buffer.put(cha);
                cha = characterReader.getNextChar();
            }
            buffer.flip();
            str = buffer.toString();
            buffer.clear();



            countWords(str);

            System.out.println(wordFrequency);

        }
    }catch(EOFException e)

    {
        x = false;
    }


private static void countWords(String word)
        {

                if (wordFrequency.containsKey(word))
                {
                    Integer count = wordFrequency.get(word);
                    count++;
                    wordFrequency.put(word, count);
                    } else {
                    wordFrequency.put(word, 1);
                }
        }

public static void main (String args[])
{
    CharacterReader cr = new SimpleCharacterReader();
    findResult(cr);
}

Upvotes: 0

Views: 181

Answers (3)

karkiRiks
karkiRiks

Reputation: 1

Try moving System.out.println(wordFrequency); out of the while loop braces...

Upvotes: 0

Virtually Real
Virtually Real

Reputation: 1685

Move

System.out.println(wordFrequency);

To outside the try statement. You are printing the whole set after each word.

Upvotes: 1

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

It's all in where you've placed your System.out.println. You've got it inside of the loop!

    while(x) {
        // .....

        countWords(str);

        System.out.println(wordFrequency);
    }

Solution: do it after the loop.

    while(x) {
        // .....

        countWords(str);

    }
    System.out.println(wordFrequency);

Upvotes: 0

Related Questions