当前位置: 代码迷 >> Java相关 >> 新人请教大神们一道小题!
  详细解决方案

新人请教大神们一道小题!

热度:95   发布时间:2012-09-23 21:02:17.0
新人请教大神们一道小题!
“编一个程序CountNum.java,生成并输出30个0~9之间的随机整数,并统计0~9这10个数字分别出现了多少次。”主要是统计这部分不会,请大神帮帮小弟,谢谢!
搜索更多相关的解决方案: 统计  

----------------解决方案--------------------------------------------------------
程序代码:
import java.util.Random;
import java.util.HashMap;

public class CountNum {
    public static void main(String[] args) {
        HashMap<Integer, Integer> map = new HashMap<>();
        Random rand = new Random();
        for (int i = 0; i < 30; ++i) {
            int r = rand.nextInt(10);
            Integer freq = map.get(r);
            map.put(r, freq == null ? 1 : freq + 1);
        }
        System.out.println(map);
    }
}

----------------解决方案--------------------------------------------------------
怎么编译错误?
----------------解决方案--------------------------------------------------------
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
可能你的JDK版本太低了吧?
把红色那段补上去试试。
----------------解决方案--------------------------------------------------------
回复 4楼 lz1091914999
现在可以了,但我不理解,如果可以的话解释下,谢谢!
----------------解决方案--------------------------------------------------------
用下面这个可能会好懂些
import java.util.Random;public class test{    public static void main(String[] args){        int[] count = new int[10];        for(int i=0;i<10;i++)            count[i]=0;        Random rand = new Random();        for (int i = 0; i < 30; ++i) {            int r = rand.nextInt(10);            count[r]++;        }        for(int i=0;i<10;i++)            System.out.println("num " + i + " appears " + count[i] + " times");    }}

[ 本帖最后由 森罗万象 于 2012-9-28 02:58 编辑 ]
----------------解决方案--------------------------------------------------------
o
----------------解决方案--------------------------------------------------------
回复 2楼 lz1091914999
果然是大神,用到泛型了,,,,math.random()也可以呀
----------------解决方案--------------------------------------------------------
  相关解决方案