将随机数值打印到数组

时间:2014-05-01 04:56:01

标签: java arrays random

我对如何在Java中执行此特定过程感到困惑。

我必须使用RNG将特定数量的值打印到数组中,但我无法弄清楚的部分是如何为每个数组元素赋予一个值,如果RNG给出该值,则该值将增加值。例如:

阵列

0
1 2

如果RNG返回2,则递增数组中的2,然后像这样显示

0 1 2 1(如,它滚动了2次,所以它现在1)

我在做用户输入和RNG部分方面没有问题,但我不知道如何显示它 任何帮助将不胜感激,谢谢。

到目前为止

代码

public static void main(String [] args){

    Scanner input = new Scanner( System.in); //Declares the scanner
    Random randomNumbers = new Random(); // Declares the random property you will need later

    //Variables
    int randomrequest = 0; //Declares randomnum as a integer with a value of 0, this is what the user inputs as the number they want.
    int randomrange = 0; //Declares the number for the number range for the random number generator
    int randomcounter = 0;//Declares the counter you will need later as 0
    int result = 0; //This variable is for the random number generation result


    System.out.printf( "How many random numbers do you want to generate?" ); //asks for the number to generate

    randomrequest = input.nextInt(); //Makes the user enter a value to and then stores it in this variable.

    System.out.printf( "What is the number of values for each random draw?" ); //asks for the number range

    randomrange = input.nextInt(); //See above

    //Ok now we have to use the inputed information to do the rest of the processing before we can display it

    //First, create the array and give it the size equal to the number range entered

    int[] array = new int[ randomrange ]; // Declares the array with the amount of slots for each outcome

    //We need to use a loop here to make sure it rolls the RNG enough times 

    while (randomcounter != randomrequest) { //This tells it generate a random number until the counter equals the entered amount.

        result = randomNumbers.nextInt( randomrange ); //Generates a random number within the range given


        randomcounter += 1; //increments the counter, so that it will eventually equal the entered number, and stop.

    }//End of do while


    }//end of Public static void

}//End of entire class

2 个答案:

答案 0 :(得分:1)

如果我正确地解释你的问题,你可以尝试的一件事是让数组中的每个元素成为其索引的计数器。因此,如果随机数生成器生成2,则会增加array[2]中的值。

简明的说法可能是:

while (randomCounter++ != randomRequest) {
    array[randomNumbers.nextInt(randomRange)]++;
}

答案 1 :(得分:1)

以下代码适用于您的解决方案:

while (randomcounter != randomrequest) {
    result = randomNumbers.nextInt(randomrange);
    array[result] += 1;
    randomcounter +=1;
    for (int i = 0; i < array.length; i++)
    {
        system.out.print(array[i] + " ");
    }
    system.out.println();
}