weixin_43232310 2019-07-12 16:35 采纳率: 0%
浏览 394

麻烦请教下当字符串中有多个字符数量相同时,怎么同时输出?即输出成“出现最多的字符有多个”

麻烦请教下当字符串中有多个字符数量相同时,怎么同时输出?即输出成“出现最多的字符有多个”
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;
}

}

  • 写回答

2条回答 默认 最新

  • 两个娃他爹 2019-07-12 17:05
    关注
      public static void main(String[] args) {
            String str = "aaabbbbcccdddddd";
            Map<String,Integer> map = new HashMap<>();
            for(int i=0;i<str.length();i++){
                if(map.containsKey(String.valueOf(str.charAt(i)))){
                    map.put(String.valueOf(str.charAt(i)),map.get(String.valueOf(str.charAt(i)))+1);
                }else{
                    map.put(String.valueOf(str.charAt(i)),1);
                }
            }
            int max=0;
            String maxStr = null;
            for(String s:map.keySet()){
                int count = map.get(s);
                if(count>max){
                    max=count;
                    maxStr = s;
                }
            }
            System.out.println("字符"+maxStr+"出现"+max+"次");
        }
    
    评论

报告相同问题?

问题事件

  • 请详细说明问题背景 10月8日

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集