计算随机生成的数字中的出现次数

时间:2013-05-07 22:22:32

标签: java random

我有一个Java程序,它在0到9之间生成100个随机整数,我需要让它显示每个数字的计数。例如:

*************************************************************************
Generating 100 random integers between 0 and 9
Number 1 = 3
Number 2 = 0
… (your program must display all generated numbers)
Number 100 = 8
*************************************************************************
0 occurs 1 time
1 occurs 9 times
2 occurs 18 times
3 occurs 20 times
4 occurs 5 times
5 occurs 20 times
6 occurs 1 time
7 occurs 1 time
8 occurs 25 times
9 occurs 0 time
*************************************************************************

到目前为止,我有这么多:

 import java.util.Random;
    public class World {
    public static void main(String[] args) {

        public void generateNumber(){
System.out.println("*************************************************************************");
           System.out.println("Generating 100 random integers between 0 and 9");

        Random aGenerator = new Random();

        int randomArray[]=new int[101];
        int countArray[]=new int[10];

        //generate the numbers and store into an array
        int j;
        for(int i=1; i<101; ++i) {
            j=i;
                randomArray[i]=aGenerator.nextInt(10);

                //displaying numbers
                  System.out.println("Number " + j + " = " + randomArray[i]);

            }



 System.out.println("*************************************************************************");

//counting the numbers
for(int i=1;i<100;i++){
    countArray[randomArray[i]-1] = countArray[randomArray[i]-1]+1;

//displaying the counts
    j=i;
    System.out.println(randomArray[i]+" occurs "+countArray[i]+ " times");

    }




           }
}
}

并且生成和显示随机数工作正常,但是,计数部分看起来像这样

*************************************************************************
5 occurs 0 times
7 occurs 0 times
7 occurs 0 times
9 occurs 1 times
2 occurs 0 times
2 occurs 2 times
1 occurs 0 times
4 occurs 1 times
    at Generator.generateNumber(2 appears 0 times
Generator.java:33)
    at World.main(World.java:17)

请告诉我哪个部分做错了?非常感谢你的时间!

1 个答案:

答案 0 :(得分:3)

您的代码比需要的更复杂。只需使用:

//to store the counts
for (int r : randomArray)
    countArray[r]++;

//to access the counts
for (int x = 0; x < countArray.length; x++) {
    System.out.println("" + x + " occurs " + countArray[x] + " times");
}