zoukankan      html  css  js  c++  java
  • 使用Map统计随机数出现的次数

    使用Map统计随机数出现的次数

    题:统计随机数字出现的次数,以及出现次数最多的数字和次数分别是多少?

    解答: 使用Map不可存储相同键的属性来统计,如果在Map中没有出现该数字,那么它出现的次数就为1;如果在Map中已经存在该数字,那么把该值出现的次数+1

    import java.util.*;
    
    public class MapCountWords {
        public static void main(String[] args) {
            /**
            * 统计随机数字出现的次数,以及出现次数最多的次数是多少?
            */
            TreeMap<Integer,Integer> map = new TreeMap();
            for (int i = 0; i < 50; i++) {
                int num = (int) (Math.random() * 40 + 10);
                //如果该值在map中没有出现,则出现次数为1
                if (map.get(new Integer(num)) == null) {
                    map.put(new Integer(num), 1);
                } else {
                    //如果该值在map中存在,则把出现次数+1
                    map.put(num, ((Integer)map.get(num)).intValue()+1);
                }
            }
            for (Map.Entry<Integer,Integer> entry : map.entrySet()){
                System.out.println(entry);
            }
            //计算最大的次数
            Collection collect =  map.values();
            Integer max = (Integer) Collections.max(collect);
            System.out.println("出现最多次数为:" + max);
        }
    }

     

  • 相关阅读:
    secureCRT使用pem私钥
    常用的GoLang包工具
    解决vs code 调试golang时字符串显示不全的问题
    git 常用操作
    go sqlx db.Query需手动释放
    go dlv 调试
    Ambari中superset-hive认证
    HDP3.x hive load data local inpath 设置
    dolphinscheduler-调度
    sourceTree 提交错误
  • 原文地址:https://www.cnblogs.com/eathertan/p/12584582.html
Copyright © 2011-2022 走看看