• 用JAVA实现找出输入字符串中的出现次数最多的字符及其次数;


     1 //通过Map 类实现,通过键值对的方式,可以将输入的字符串的每一个字符,作为键,每个字符出现的次数作为值:如下:
     2 
     3 public class Find {
     4   public static void main(String[] args){
     5     String scan=new Scanner(System.in).nextLine();//获取键盘上输入的字符串;
     6     Map<Character,Integer> map = new HashMap<Character,Integer>();//新建一个HashMap对象;    
     7        //通过FOR循环,把String的键值存放到map
     8     for(int i=0;i<scan.length();i++){
     9       char temp=scan.charAt(i);//通过循环,找到字符串的每一位字符并存入到temp中;
    10       if(map.containsKey(temp)){//如果map里面有temp这个字符
    11         map.put(temp, map.get(temp)+1);//把temp的值加1;
    12       }else{//如果map里面没有temp这个字符,
    13         map.put(temp, 1);//把temp的值设为1;
    14       }
    15     }
    16 /*Collection c = map.entrySet();
    17 Iterator it = c.iterator();
    18 Map.Entry<Character, Integer> entry;
    19 while(it.hasNext()){
    20 entry = (Map.Entry<Character, Integer>) it.next();
    21 }
    22 */
    23     int maxnum = Collections.max(map.values());//调用Collections类的max方法,获取map的值的集合;并找出最大的那个值;
    24     Set<Character> set = new HashSet<Character>();//建立一个set对象
    25     for(Map.Entry<Character, Integer> entry1:map.entrySet()){ //通过集合的循环,把map的值放到entry1里,通过entry1找到值最大的maxnum的key;
    26         if(entry1.getValue()==maxnum){
    27            set.add(entry1.getKey());
    28         }
    29     }
    30 System.out.println("出现次数最多的字母为:"+set+" 最多出现次数为"+maxnum);
    31 
    32  }
    33 
    34 }
  • 相关阅读:
    听较强节奏的歌曲,能让你更长时间投入到学习中
    小康网站维护笔记
    apache基础
    python安装多版本
    apache负载调优
    docker 进阶
    openstack 网络更改版
    linux 搭建testlink的问题总结
    26. Remove Duplicates from Sorted Array(LeetCode)
    Add to List 172. Factorial Trailing Zeroes(LeetCode)
  • 原文地址:https://www.cnblogs.com/lelexiong/p/8727419.html
Copyright © 2020-2023  润新知