麻烦请教下当字符串中有多个字符数量相同时,怎么同时输出?即输出成“出现最多的字符有多个”
public class exam4 {
/**
* Q4.设计一个函数,统计一个字符串中出现频率最高的字符及其出现次数,并利用该函数对用户输入的任意字符串进行统计。
* @author GTzzz
* @param args
*/
public static void main(String[] args) {
String word = "aaaddd";
int num = 0;
char name = 0;
Map hashMap = countWords(word);
for(Map.Entry entry: hashMap.entrySet()){
System.out.println("字符:"+entry.getKey()+",数量:"+entry.getValue());
if ((Integer)entry.getValue() > num ) {
num = (Integer)entry.getValue();
name = (char) entry.getKey();
}
}
String name1 = String.valueOf(name);
System.out.println("出现最多的字符:"+name1+",数量为:"+num);
}
public static Map<Character,Integer> countWords(String word){
Map<Character,Integer> map = new HashMap<Character, Integer>();
for(int i = 0; i < word.length(); i++){
char ch = word.charAt(i);
/*System.out.println("ch:"+ch);
System.out.println("map.get:"+map.get(ch));*/
if(map.get(ch) != null){
map.put(ch,map.get(ch)+1);
}else{
map.put(ch,1);
}
}
return map;
}
}