如何将 java.util.random 转换为 int

我正在使用带有种子的 java.util.random(new Random(System.currentTimeMillis())

  • 我需要将其转换为 int(我的业务逻辑)

  • 我尝试使用 .nextInt(),但没有帮助

//我的业务逻辑--下面的代码是循环的,目的是每次生成不同的随机数//

int randomNumber=(int) Math.floor(inputParam1 * (new Random(System.currentTimeMillis())).nextInt()));

预期输出:每次生成一个新的随机数,int格式

实际输出: - 使用 nextInt() 它每次生成相同的数字 - 如果不转换为 Int,我无法将“随机”
数据类型与上面显示的 int 变量一起使用


MMMHUHU
浏览 204回答 3
3回答

泛舟湖上清波郎朗

不要在每次要生成 Double 时都创建 Random 的新实例。您可以创建一个实例,然后在需要新的替身时调用它。Random rand = new Random(System.currentTimeMillis());// loop starts here  double randomNumber = Math.floor(inputParam1 * rand.nextDouble());// If you want an integer up to inputParam1 as it seems, you can do:  int randomInt = (int) randomNumber;您也可以Math.random()像已经建议的那样使用。

ITMISS

将下面的代码转换为 int 是没有意义的。Math.floor(inputParam1 * (new Random(System.currentTimeMillis())).nextDouble()))请检查这个答案Using Random Number Generator with Current Time vs without上面链接中最重要的部分:如果你希望你的随机序列在运行之间是相同的,你可以指定一个种子。

白板的微信

我不知道你为什么要把它转换成 int双随机数=新随机(System.currentTimeMillis()).nextDouble();这将给出一个介于 0 和 1 之间的随机双数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java