Reputation: 1
I am writing a Frequency Counter that reads a given file returns the frequency (in percentage) of each letter in the file. My code so far reads the file and lists the count of each letter occurring in the file. I cannot figure out how combine all of the counts in order to generate the percentages instead. Below is my code and please forgive if I didn't use the code blocks correctly. Still learning all of this stuff.
import java.io.File;
import java.util.*;
public class FrequencyCounter
{
public static void main(String[] args )
{
char[] capital = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char[] small = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
Scanner scan;
try
{
scan = new Scanner(new File("c://Users//Mikel//Desktop//School Work//CIS407//Week1//mary.txt"));
}
catch (Exception e)
{
System.out.println("File not found");
return;
}
int[] count = new int[26];
while(scan.hasNextLine())
{
String line = scan.nextLine();
System.out.println("Line read: " + line);
char[] digit = line.toCharArray();
for(int i = 0; i < digit.length; i++)
{
for(int j = 0; j < 26; j++)
{
if(digit[i] == capital[j] || digit[i] == small[j])
{
count[j]++;
break;
}
}
}
}
for (int i = 0; i < 26; i++)
{
System.out.print(" " + capital[i]);
System.out.println(" " + (count[i]));
}
}
}
Upvotes: 0
Views: 927
Reputation: 726809
Your code can be simplified a lot by observing that ch - 'a'
is an integer expression returning the index of the lowercase letter, and ch - 'A'
does the same thing for the uppercase letters. So the nested loop and the arrays of upper and lower cases are not necessary. You can tell if a character is uppercase or lowercase by calling Char.isUpperCase(ch)
or Char.isLowerCase(ch)
.
You can get percentages by adding up all counts, and calculating percentages the usual way:
double pct = (count[i]*100.0) / total;
Upvotes: 1
Reputation: 12266
There are many ways you could do this. As you noted the next step is to come up with the totals. Which would mean looping through the two arrays and storing the total in a separate variable. From there you can divide each count by the total to come with a percentage.
In other words, you need two more loops to complete the task.
You might also consider breaking the code out into methods. Say one per loop so it reads more like:
countLetters();
calculateTotal();
printPercentages();
Also, you can make the code simpler. Rather than looping from 0 to 25 and checking if it is equals, you can call Character.toLowerCase(digit[i]) to get the lower case one [so you only have to deal with one]. Then you can subtract - 'a' from your letter to get the index without using the array of 26 characters at all.
Upvotes: 0