黑马程序员技术交流社区

标题: 集合面试题之 摇撒子 难度系数3.5 [打印本页]

作者: wolfking0608    时间: 2016-10-9 13:09
标题: 集合面试题之 摇撒子 难度系数3.5
/**
* 摇色子摇50次生成六个随机数,统计每个数出现的次数
*  耗时:10分钟
*  日期和代码统计 25日第五个代码
*  代码效率:3.7行/min
*  情绪状态: 一般
*  思路分析及时间: 3分钟
*     1.首先要定义一个随机数,这个随机数在1-6之间
*     2.这个随机数要变化50次
*     3.把五十出现的数量放在集合中,并且是双列集合.用TreeMap对他们进行排序
*     4.最后遍历这个集合
*       打印健和值
*/
public class 摇色子 {
        public static void main(String[] args) {
                TreeMap<Integer, Integer> tm = new TreeMap<>();
                int count=1;
                while(count<=50){
                        int num =(int)(Math.random()*6+1);
                        if(!tm.containsKey(num)){
                                tm.put(num, 1);
                        }else{
                                tm.put(num, tm.get(num)+1);
                        }
                        count++;
                }
                for (Map.Entry<Integer, Integer> m: tm.entrySet()) {
                        System.out.println(m.getKey()+"===="+m.getValue());
                }
        }

}

作者: u8u8u80pp    时间: 2016-10-9 22:52
贴上标签,有时间看
作者: 三人壹大    时间: 2016-10-9 23:19
if else可以换成三元运算符 第18天视频
作者: 回根的落叶    时间: 2016-10-10 00:13
本帖最后由 回根的落叶 于 2016-10-10 00:15 编辑

while循环里面的可以改为
[Java] 纯文本查看 复制代码
 while(count<=50){
       int num =new Random().nextInt(6)+1;
       tm.put(num, !tm.containsKey(num)?1 : tm.get(Key)+1);
       count++;
}






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2