个人作业8-单词统计
统计在一篇文章中单词出现的频率
package com.Chazhao; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.DecimalFormat; public class test{ public static void main(String[]args) throws IOException{ DecimalFormat format=new DecimalFormat("0.00"); StringBuffer str=new StringBuffer(""); File file=new File("C:\\\\Users\\\\hp\\\\Desktop\\\\JAVA.txt"); int sum[]=new int[26]; @SuppressWarnings("unused") int th=0; int k=0; try { @SuppressWarnings("resource") FileReader fr=new FileReader(file); int ch=0; while((ch=fr.read())!=-1) str.append((char)ch); }catch (FileNotFoundException e) { e.printStackTrace(); } for(int i=0;i<str.length();i++) { char c=str.charAt(i); if(Character.isLetter(c)) { if(c=='t'&&str.charAt(i+1)=='h'&&str.charAt(i+2)=='e') th++; int a=(int)c; if(Character.isLowerCase(c)) k=a-97; else k=a-65; sum[k]++; } } for(int i=0;i<26;i++) if(sum[i]!=0) System.out.println((char)(65+i)+"出现频率为"+format.format((double)sum[i]/str.length()*100)+"%"); } }