简体   繁体   English

使用math.random在Java中生成一定数量的随机数

[英]Using math.random to generate a certain amount of random numbers in java

I need help making a program in java that lets you write a number in textField and then generate that amount of random numbers from 0-9 using i = (int) (Math.random() * 10.0). 我需要在Java中制作程序的帮助,该程序允许您在textField中写一个数字,然后使用i =(int)(Math.random()* 10.0)从0-9生成一定数量的随机数。 For example if I would write 5 in the textField the program would generate 5 random numbers from 0-9. 例如,如果我在textField中写入5,则程序将从0-9生成5个随机数。

Thanks 谢谢

Using the new Java 8 streams API: 使用新的Java 8流API:

int n = Integer.parseInt(myTextField.getText());
int[] random = ThreadLocalRandom.current().ints(0, 10).limit(n).toArray();
  • uses the current thread local random (recommended over creating a new Random instance) 使用当前线程局部随机数(建议在创建新的Random实例时使用)
  • creates a random stream of integers in the range [0..10) -> 0..9 创建范围为[0..10)-> 0..9的随机整数流
  • Stream terminates after n numbers have been generated 流在生成n个数字后终止
  • the stream result is collected and returned as an array 流结果被收集并作为数组返回
int x = value entered in textfield;
int generatedRandomNumber = 0;
java.util.Random rand = new java.util.Random();
for(int i=0 ; i<x ; i++) {
    generatedRandomNumber=rand.nextInt(10);//here you have your random number, do whatever you want....
}

Ok since you want to use the Math.random() method try the following: 好的,因为您想使用Math.random()方法,请尝试以下操作:

    int times = 5;//how many numbers to output

    for(int i = 0; i < times; i++)
    {
        System.out.println((int)(Math.random()*10));
        //you must cast the output of Math.random() to int since it returns double values
    }

I multiplied by 10 because Math.random() returns a value greater than or equal to 0.0 and less than 1.0. 我乘以10是因为Math.random()返回的值大于或等于0.0且小于1.0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM