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);
        }
    }

     

  • 相关阅读:
    KTorrent 2.1
    Krusader-双面板文件治理器
    VirtualBox 1.3.4
    QEMU 0.9.0 & QEMU Accelerator 1.3.0pre10
    Sweep:音频编辑器材
    USBSink-优盘同步备份东西
    玩转 MPlayer(1)
    玩转 MPlayer(2)
    活动目录之迁移
    再学 GDI+[26]: TGPPen 画笔对齐 SetAlignment
  • 原文地址:https://www.cnblogs.com/eathertan/p/12584582.html
Copyright © 2011-2022 走看看