且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我怎样才能在groovy中使用随机数字?

更新时间:2023-01-19 17:12:00

没有像 java.util.Random.getRandomDigits



随机数使用nextInt:

  return random.nextInt(10 ** num)

您还应该创建随机对象

 随机random = new Random()

每次你想要一个新的随机数时,你都不应该创建一个新的随机对象。这样做会破坏随机性。

I use this method:

def getRandomNumber(int num){
    Random random = new Random()
    return random.getRandomDigits(num)
}

when I call it I write println getRandomNumber(4)

but I have an error

No signature of method: java.util.Random.getRandomDigits() is applicable for argument types: (java.lang.Integer) values: [4]

Note: I use this method in another groovy class and it works properly without any error

There is no such method as java.util.Random.getRandomDigits.

To get a random number use nextInt:

return random.nextInt(10 ** num)

Also you should create the random object once when your application starts:

Random random = new Random()

You should not create a new random object every time you want a new random number. Doing this destroys the randomness.