Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use random numbers in groovy?

Tags:

random

groovy

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.

like image 660
Georgian Citizen Avatar asked Nov 22 '10 09:11

Georgian Citizen


People also ask

How to generate a random number in Groovy?

Groovy - random() The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math. random < 1.0. Different ranges can be achieved by using arithmetic.

How do you generate a random 5 digit number in Java?

Just generate a int value = random. nextInt(100000) so that you will obtain a value in [0,99999] . Now your definition of 5 digits pin is not precise, 40 could be interpreted as 00040 so it's still 5 digits if you pad it.

How does Soapui generate random numbers?

setPropertyValue("TransID", String. valueOf((int)Math. random()*1000000000) );


1 Answers

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.

like image 179
Mark Byers Avatar answered Sep 26 '22 03:09

Mark Byers