gpt4 book ai didi

java - Random.nextInt() 产生非常相似的数字?

转载 作者:搜寻专家 更新时间:2023-11-01 03:04:29 24 4
gpt4 key购买 nike

我用 Java 编写了一个类来生成一个随机的 Int 数组,其中数字介于 (0-100) 之间:

    import java.util.Random;

public class RandomClass{
private Random randNum;

public RandomClass() {
randNum = new Random();
}

public int[] generateRandomArray(int arraySize){
int[] theArray = new int[arraySize];
for(int i = 0; i < arraySize; i++){
theArray[i] = randNum.nextInt(101);
}
return theArray;
}
}

出于某种原因,当我运行我的程序时,我每次都会在我的数组输出中得到一个重复的类似数字序列。

这是一个示例,显示程序在不同时间运行了 3 次:

Array result: [65, 71, 71, 71, 78, 78, 78, 78, 78, 78]

Array result: [40, 55, 55, 55, 62, 62, 62, 70, 77, 77]

Array result: [56, 56, 73, 73, 73, 73, 77, 77, 77, 77]

为什么会这样?是因为 Random 函数是基于时间的,并且循环运行得太快才能返回新的“随机”数字吗?还是别的什么原因?我该如何解决这个问题?

最佳答案

你贴的代码没有问题,只是添加了一个main方法,你会看到:

public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
int[] ints = new RandomClass().generateRandomArray(10);
System.out.println("RandomClass::main: ints = " + Arrays.toString(ints));
}
}

它打印出非常不同的随机数。问题出在其他地方。

关于java - Random.nextInt() 产生非常相似的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27414799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com