在我长时间的努力下我终于写完了那个简单的任务,我尝试了好几种方法后,终于成功了,也是醉了。
为了能同时显示出现次数最多的字母以及次数,我在出现一次错误后改用了相似的两段程序,我成功了。
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Count {
public static void main(String[] args) {
String path = "C:/Users/86173/Desktop/EnglishArtical.txt";
File file = new File(path);
int[] count=new int[26];
int[] count2=new int[26];
for(int i=0;i<26;i++)
{
char a='A';
int n=((int)a+i);
char des = (char)n;
int count1 = process(file, des);
count[i]=count1;
System.out.println("字符" + des + "在出现" + count[i]+"次");
}
for(int i=0;i<26;i++)
{
char a='a';
int n=((int)a+i);
char des = (char)n;
int count1 = process(file, des);
count2[i]=count1;
System.out.println("字符" + des + "出现" + count2[i]+"次");
}
int j=0,k=0;
int maxIndex1 = count[0];
int minIndex1 = count[0];
for (int i = 0; i < count.length; i++) {
if(maxIndex1 < count[i]){
maxIndex1 = count[i];
j=i;
}
if(minIndex1 > count[i]){
minIndex1 = count[i];
}
}
int maxIndex2 = count2[0];
int minIndex2 = count2[0];
for (int i = 0; i < count2.length; i++) {
if(maxIndex2 < count2[i]){
maxIndex2 = count2[i];
k=i;
}
if(minIndex2 > count2[i]){
minIndex2 = count2[i];
}
}
if(maxIndex1>maxIndex2)
{ char a='A';
int n=((int)a+j);
char des = (char)n;
System.out.println("字符" + des + "在出现的次数最多为:" +maxIndex1);
}
else if(maxIndex1<maxIndex2)
{ char a='a';
int n=((int)a+k);
char des = (char)n;
System.out.println("字符" + des + "在出现的次数最多为:" +maxIndex2);
}
}
public static int process(File file, char c) {
int count = 0;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String temp = "";
while ((temp = br.readLine()) != null) {
char[] des = temp.trim().toCharArray();
for (int i = 0; i < des.length; i++) {
if (des[i] == c){
count++;
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return count;
}
}