java作业4.12(二)


2、统计出C:\temp.txt中,26个字母分别出现的次数(不区分大小写),将统计结果写到D:\result.txt中。

import java.io.*;

public class iioo1 {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\15844\\Desktop\\新建文件夹\\test1.txt");
        File output = new File("C:\\Users\\15844\\Desktop\\新建文件夹\\test3.txt");
        FileReader fi = new FileReader(file);
        BufferedReader br = new BufferedReader(fi);
        FileWriter fw = new FileWriter(output);
        String s = br.readLine();
        char[] a = s.toCharArray();
        for (int i = 0; i <a.length ; i++) {
            if(a[i]>='A'&&a[i]<='Z')
                a[i] = (char)(a[i]-'A'+'a');
        }
        s = String.valueOf(a);
        getNums(s,fw);
    }
    public static void getNums(String str, FileWriter fw) throws IOException {
        int[][] nums = new int[26][2];//第一位放字母出现的次数,第二位放首次出现该字母的索引
        char[] chs = str.toCharArray();
        for (int i = 0; i <chs.length ; i++) {
            if(chs[i]>=97&&chs[i]<=123){
                if(nums[chs[i]-97][0]==0){
                    nums[chs[i]-97][1] = i;
                }
                nums[chs[i]-97][0]++;
            }
        }
        for (int i = 0; i <nums.length ; i++) {
            if(nums[i][0] != 0){
                char j = (char)(i+97);
                String t = j + "出现的次数为:" +nums[i][0];
                fw.write(t);
            }
            fw.write("\r\n");
        }
        fw.flush();
        fw.close();
    }
}

你可能感兴趣的:(java作业4.12(二))