public class TestDemo1 {
public static void main(String[] args) {
HashMap<Character,Integer> hashMap = new HashMap();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一英语:");
String s = scanner.nextLine();
String regex = "[a-zA-Z ,.]*";
boolean b = s.matches(regex);
if (!b){
System.out.println("你的输入有误");
return;
}
//除去空格逗号句号
String s1 = s.replaceAll("[ ,.]", "");
//遍历字符串
for (int i = 0; i < s1.length(); i++) {
int value = 1;
//得到集合的Key
Set keySet = hashMap.keySet();
char c = s1.charAt(i);
//判断集合是否为空
if(keySet==null){
hashMap.put(c,value);
continue;
//如果Keyset中已经存在当前字母则将它的Value取出来加一再放进去
}else if(keySet.contains(c)){
int i1 = hashMap.get(c);
i1++;
hashMap.put(c, i1);
continue;
}else {
hashMap.put(c,value);
}
}
System.out.println(hashMap.toString());
}
}
小编是还没入门的菜鸟求大神更优化的代码