public class FrequencyCalculator {public static void main(String[] args){//定义需要计算字母出现频率的文本String text="some off#acebooksea3rl255 yinvestorssoldofftheirstockatthefirs" +"tchancetheygotbutceomarkzuckerbergishangingontohissharesforatleast" +"thenextyearzuckerbergsinterviewwilltakeplaceonseptembereleventhinsa" +"nfranciscothesocialnetworkhasnearlyabillionusersbutthecompanyhasstru" +"ggledtomaintainmomentumsinceitsipo";//定义26个字母String letter="abcdefghijklmnopqrstuvwxyz";calculate(text,letter);}public static void calculate(String text,String letter){//定义存储各字母出现次数的数组int []counter=new int[26];//定义存储各字母出现频率的数组double []f4=new double[26];//定义字母总个数的计数器。排除标点符号,空格和数字。int total_counter=0;//将string类型转化成char类型char[] text_tr=text.toCharArray();char[] letter_tr=letter.toCharArray();//计算各字母出现次数以及总字母数//外层循环,遍历26个字母for(int i=0;i<26;i++){//内层循环,遍历待计算文本for(int j=0;j<text_tr.length;j++){//字母每在文本中出现一次,字母计数器加一,总字母个数计数器加一if(text_tr[j]==letter_tr[i]){counter[i]++;total_counter++;}}}//计算各字母出现频率,结果保留小数点后4位for(int i=0;i<26;i++){//将int类型转换成double类型double counter_d=(double) counter[i];double total_d=(double) total_counter;//字母出现频率=字母出现次数/总的字母数double fre=counter_d/total_d;//保留小数点后4位f4[i]=(double) (Math.round(fre*10000)/10000.0); //输出结果System.out.println(letter_tr[i]+" frequency is "+f4[i]);}}
}
以上代码运行结果如下图: