# Java letter frequency

• March 24th, 2013, 02:49 PM
maple1100
Java letter frequency
Could someone give me some suggestions on how I could code a program that go through a string and determine the frequency of each letters? I can't use char so the only thing I have left is array. I was thinking of going comparing the substring of the string 1 by 1 and each time it match a letter in the alphabet array, I would make the letter counter to be ++. But this would mean I have to create 26 different int variable to keep count of the individual letters. Any ideals on how I can avoid making 26 counter variable for the letter? Thanks. (I would provide the code but the current code I have consist of the 26 variable which is not much useful)

** I thought of something, I will edit the post with the code in a few min.
• March 24th, 2013, 02:55 PM
Norm
Re: Java letter frequency
Quote:

how I can avoid making 26 counter variable
Use an array.

Quote:

I can't use char
Does that mean you can only work with Strings?

Are you using java version 1.7? It allows Strings in switch statements.
• March 24th, 2013, 03:05 PM
maple1100
Re: Java letter frequency
I used your suggestion of using an array. It worked. Thanks you so much for the suggestion!

-Can you help me figure out why percent[x] is giving me 0.00? Thanks
Code :

int total = 0 ;
for(int i = 0 ; i < rate.length; i++)
{
total += rate[i];
}
double [] percent = new double[26];
System.out.println("Total is "+total);
System.out.println("Rate at [0] is " + rate[0]);
for(int x = 0 ; x < rate.length;x++)
{
percent[x] = (rate[x] / total);
}

System.out.println("Percent at [0] is "+percent[0]);

Total is 52
Rate at [0] is 7
Percent at [0] is 0.0

** It work when I cast rate[] to an int but why does this occur? Isn't the percent[] is a double so wouldn't it result in a double without me casting the rate[]?