package com.heima.test;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
public class Demo1 {
/**
* 输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
*/
public static void main(String[] args) {
String line = getLine();
char[] arr = line.toCharArray();
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer> ();
for (char cha : arr) {
tm.put(cha, tm.containsKey(cha) ? tm.get(cha) + 1 : 1);
}
Set<Character> keySet = tm.keySet();
for (Character cha : keySet) {
switch (cha) {
case '\t':
System.out.println("\\t = " + tm.get(cha));
break;
case '\r':
System.out.println("\\r = " + tm.get(cha));
break;
case '\n':
System.out.println("\\n = " + tm.get(cha));
break;
default:
System.out.println(cha + " = " + tm.get(cha));
break;
}
}
}
private static String getLine() {
System.out.println("请输入一个字符串:");
Scanner sc = new Scanner(System.in);
return sc.nextLine();
}
} |