计数100个随机数

时间:2017-04-22 02:41:07

标签: java arrays for-loop random

我想在0到9之间生成100个随机数,并显示每个数字的计数

此解决方案是否正确?我想改进,我能做得更好吗?

java.util.Scanner k = new Scanner(System.in);

int[] numbers = new int[100];

for (int i = 0;i<numbers.length;i++)
{
    numbers[i] = (int) (Math.random() * 10);
}

int [] counts = new int[10];

for (int i = 0;i<numbers.length;i++)
{
    counts[numbers[i]%numbers.length]++;
}

for (int i=0;i<counts.length;i++)
{
    if (counts[i]>1)
        System.out.println(i+1+" Generates: "+(counts[i])+" times");
    else
        System.out.println(i+1+" Generated: "+(counts[i])+" time");
}

1 个答案:

答案 0 :(得分:0)

我认为你已经推翻了这个,你只需要一个数组 - 10个值(范围0 - 9有十个唯一值),在该范围内生成一百个值,并递增数组中的值(即数字计数),然后循环显示。像,

int[] numbers = new int[10];
for (int i = 0; i < 100; i++) {
    int ndx = (int) (Math.random() * numbers.length);
    numbers[ndx]++;
}
for (int i = 0; i < numbers.length; i++) {
    System.out.printf("%d was generated %d times.%n", i, numbers[i]);
}

在Java 8+中你可以用IntStream和lambda(s)来编写上面的内容

int[] numbers = new int[10];
IntStream.range(0, 100).forEach( //
        x -> numbers[(int) (Math.random() * numbers.length)]++);
IntStream.range(0, numbers.length) //
        .forEachOrdered(x -> System.out.printf( //
                "%d was generated %d times.%n", x, numbers[x]));