笔试的题 不过我无法让a排在第一位而逗号排在最后,哪位大神能帮我指点一下,这个比较器该怎么写呢- package com.itheima;
- import java.io.*;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Iterator;
- import java.util.TreeMap;
- /*
- * 6、 把当前文件中的所有文本拷贝,存入一个txt文件,统计每个字符出现的次数并输出,例如:
- a: 21 次
- b: 15 次
- c: 15 次
- 把: 7 次
- 当: 9 次
- 前: 3 次
- ,:30 次
- * */
- class MyComp implements Comparator<Character>
- {
- public int compare(Character ch1,Character ch2)
- {
- int num = ch1.compareTo(ch2);
- //if(ch1==','&&ch2==',')
- // return 1;
- return num;
- }
- }
- public class Test06 {
- public static void main(String[] args) {
- File f = new File("data.txt");
- Comparator<Character> c = new MyComp();
- copyAndCount(f,c);
- }
- public static void copyAndCount(File f,Comparator<Character> c)
- {
- BufferedReader bufr = null;
- BufferedWriter bufw = null;
- try {
- bufr = new BufferedReader(new FileReader(f));
- bufw = new BufferedWriter(new FileWriter("copy.txt"));
- TreeMap<Character, Integer> tm = new TreeMap<Character,Integer>(c);
- int ch=0;
- int count =0;
- while((ch=bufr.read())!=-1)
- {
- bufw.write(ch);
- Integer value = tm.get((char)ch);
- if(value!=null)
- count=value;
- count++;
- tm.put((char)ch, count);
- count=0;
- }
- Iterator<Character> it = tm.keySet().iterator();
- while(it.hasNext())
- {
- char key = it.next();
- Integer time = tm.get(key);
- System.out.println(key+": "+time+" 次");
- }
- } catch (IOException e) {
- // TODO: handle exception
- System.out.println(e.toString());
- }
- finally
- {
- try {
- if(bufr!=null)
- bufr.close();
- } catch (IOException e2) {
- // TODO: handle exception
- System.out.println(e2.toString());
- }
- try {
- if(bufw!=null)
- bufw.close();
- } catch (IOException e2) {
- // TODO: handle exception
- System.out.println(e2.toString());
- }
- }
- }
- }
复制代码 |
|