Classroom Test 1

Title: output frequency of an English text file 26 occurrences of the letter, from high to low, and the percentage of occurrences of the letter display, accurate to two after the decimal point

Source:

package words;
import java.io.*;
public class potter {
public static void main(String[] args) {
String temp=null;
double []numlower=new double[26];
double []numupper=new double[26];
double sum=0;
double num[]=new double[52];
String str[]="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 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".split(" ");
File filepath=new File("D:\\poter.txt");
try {
FileReader reader=new FileReader(filepath);
BufferedReader br=new BufferedReader(reader);
try {
while((temp=br.readLine())!=null) {
for(int i=0;i<temp.length();i++) {
if(temp.charAt(i)>='a'&&temp.charAt(i)<='z')
{
numlower[(int)temp.charAt(i)-97]++;
sum++;
}
if(temp.charAt(i)>='A'&&temp.charAt(i)<='Z')
{
numupper[(int)temp.charAt(i)-65]++;
sum++;
}
}
}
}catch(IOException e){ e.printStackTrace(); }
}catch(FileNotFoundException e) { e.printStackTrace() ; }

for(int i=0;i<26;i++)
{
num[i]=numlower[i];
num[i+26]=numupper[i];
}
for(int i=0;i<52;i++)
for(int j=0;j<51-i;j++){
double numtemp;
String tempch;
if(num[j]<num[j+1])
{numtemp=num[j];num[j]=num[j+1];num[j+1]=numtemp;
tempch=str[j];num[j]=num[j+1];num[j+1]=numtemp;
}
}
for(int i=0;i<52;i++)
{System.out.print(str[i]+':'+num[i]+" ");
System.out.printf("%.2f",num[i]*100/sum);
System.out.println("%");
}
}
}

 

 First, the path need to enter text, the number of each letter is calculated, the total number of letters, arranged in alphabetical order and then

Guess you like

Origin www.cnblogs.com/PSLQYZ/p/11809565.html