zoukankan      html  css  js  c++  java
  • 用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 }
  • 相关阅读:
    定义扩展点,实现发布订阅机制
    JS阻止事件冒泡
    Virtualbox安装黑苹果
    外部Tomcat使用Java热部署利器JRebel
    在Windows server 2016上使用docker
    Tomcat加载web.xml文件的顺序详解
    IDEA反编译整个jar包
    java集合类的继承结构
    利用BodyTagSupport创建带标签体的自定义标签
    jquery实现简单弹出框
  • 原文地址:https://www.cnblogs.com/lelexiong/p/8727419.html
Copyright © 2011-2022 走看看