【问题标题】:Printing random number values to an Array将随机数值打印到数组
【发布时间】:2014-05-01 04:56:01
【问题描述】:

我对如何在 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

【问题讨论】:

  • 到目前为止你的代码是什么?
  • 我给你加进去了

标签: java arrays random


【解决方案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();
}

【讨论】:

  • 啊,谢谢,我明白了,但是如何按要求显示呢?我知道我必须使用 for 循环
  • 刚刚更新了应该工作的内容。注销记忆以前做过类似的事情,很高兴我能提供帮助。如果需要任何其他更改,请告诉我
【解决方案2】:

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

一种简洁的表达方式可能是:

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

【讨论】:

  • 听起来很有趣,我该怎么做呢?谢谢。
  • @Moiety Design 基本上明白了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-10
  • 2023-03-17
  • 2013-05-06
  • 2018-04-09
  • 2012-12-23
相关资源
最近更新 更多