0

my program reads a file of words and im trying to print the frequency of how many words start with each letter of the alphabet. but my frequency keeps coming out as "0". Can anyone help me? this is my program:

    while (in.hasNext())
    {
        words.add(in.next());
    }
    in.close();
    aFileReader.close();

    for(int i = 0; i < chars.length - 1; i++)
    {
        int counter = 0;
        for(int j = 0; j < words.size(); j++)
        {
            String temp = words.get(j);
            String letter = temp.substring(0);
            if(letter.equalsIgnoreCase(chars[i]))
                counter++;
        }
        results += chars[i] + " = " + counter + "\n";
    }
    JOptionPane.showMessageDialog(null,results);
  • Where is `chars` defined? What is its type? – Louis Wasserman Apr 02 '14 at 19:54
  • Its a String array with all the charactors of the alphabet – user3330578 Apr 02 '14 at 19:56
  • are you combining upper and lower case? I assume you're also leaving out non-letters (eg quote marks, etc) – Mar Apr 02 '14 at 19:57
  • no im ignoring the case and yes there is no non-letters! – user3330578 Apr 02 '14 at 20:00
  • `temp.substring(0)` is the entire string, `i < chars.length - 1` is going to leave off the last letter so you'll never find words beginning with Z, temp is a terrible name for a variable, you never use `j` so you could just do `for (String word : words)`, and you should use a StringBuilder to assemble the results. – David Conrad Apr 02 '14 at 20:16
  • Also, why the nested loop? Why not loop once over the words, incrementing counters for the first letters in either an array, or a map? – David Conrad Apr 02 '14 at 20:18

2 Answers2

3

Your letter substring is wrong. You're getting a substring from character 0 of temp to the end of temp. You want .substring(0, 1), or better yet, .charAt(0).

Rather than having an array of characters to compare to, you can take advantage of the fact that Java's char type is really a number.

while (in.hasNext()) {
    words.add(in.next().toLowerCase());
}
in.close();
aFileReader.close();

int[] counter = new int[24];

for(int i = 0; i < words.size(); i++) {
    String temp = words.get(i);
    int letterIndex = temp.charAt(0) - 'a'
    if(letterIndex >= 0 && letterIndex < counter.length)
        counter[letterIndex]++;
}
for (int i = 0; i < counter.length; i++) {
    results += ((char)('a' + i)) + " = " + counter[i] + "\n";
}
JOptionPane.showMessageDialog(null,results);
Mar
  • 7,765
  • 9
  • 48
  • 82
0

temp.substring (0) returns the whole temp string, you should substitute it with temp.charAt (0).

remigio
  • 4,101
  • 1
  • 26
  • 28