首页 > 解决方案 > 如何用限制为 0-20 的随机数填充数组

问题描述

我在将随机生成器放入数组时遇到问题,如何从数组中的 0-9 中获取 #20 随机数?然后你计算这些数字的出现次数。

导入 java.util.Random;

公共类 CountDigits {

public static void main(String[] args) {



    Random digit = new Random(); 

    int Random[] = new int [20];

    int Digits[] = {0,1,2,3,4,5,6,7,8,9}; 

    int Count [] = new int [10]; 


    for ( int i = 0; i < Digits.length; i++) {


        for( int j = 0; j < Random.length; j++) {

            if ( Digits [i] == Random [j] ) 
                Count[i]++; 
        }

    }


    for ( int i = 0; i < Count.length; i++) {

        if ( Count[i] == 1) 
            System.out.printf(" %d  occurs  1 time " , Digits[i] ); 

        else
            System.out.printf("%d occurs %d times" , Digits[i], Count[i]); 

    }

结果到目前为止:: 0 发生 20 次 1 发生 0 次 2 发生 0 次 3 发生 0 次 4 发生 0 次 5 发生 0 次 6 发生 0 次 7 发生 0 次 8 发生 0 次 9 发生 0 次

标签: javaarraysrandom

解决方案


您忘记为数组元素分配随机数。这个答案可以查看随机数是如何生成的。

您需要调用 Random 对象的 nextInt(an integer) 方法。如果你给它 25,它将返回一个介于 0-24 之间的随机整数。

示例用法:

Random rand = new Random();
int random_int = rand.nextInt(50); // --------> Random integer 0-49

和完整的代码

import java.util.Random;

public class Main {

    public static void main(String[] args) {


        Random digit = new Random();

        int Random[] = new int[20];

        for (int x=0;x<20;x++) {
            Random[x] = digit.nextInt(10);
        }

        int Digits[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

        int Count[] = new int[10];


        for (int i = 0; i < Digits.length; i++) {


            for (int j = 0; j < Random.length; j++) {

                if (Digits[i] == Random[j])
                    Count[i]++;
            }

        }


        for (int i = 0; i < Count.length; i++) {

            if (Count[i] == 1)
                System.out.printf(" %d  occurs  1 time ", Digits[i]);

            else
                System.out.printf("%d occurs %d times", Digits[i], Count[i]);

        }
    }
}

输出:

0 occurs 2 times1 occurs 2 times 2  occurs  1 time 3 occurs 3 times4 occurs 6 times 5  occurs  1 time 6 occurs 2 times7 occurs 0 times 8  occurs  1 time 9 occurs 2 times

您可以像这样打印随机数

 for (int x=0;x<20;x++) {
        System.out.println(Random[x]);
    }

推荐阅读