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
Generate pseudo random numbers between 1 and an [UPPER_LIMIT]
You can use the following to generate a number between 1 and an upper limit.
Math.abs(new Random().nextInt() % [UPPER_LIMIT]) + 1
Here is a specific example:
Example - Generate pseudo random numbers in the range 1 to 600:
This will generate a random number within a range for you. In this case 1-600. You can change the value 600 to anything you need in the range of integers.
Generate pseudo random numbers between a [LOWER_LIMIT] and an [UPPER_LIMIT]
If you want to use a lower bound that is not equal to 1 then you can use the following formula.
Math.abs(new Random().nextInt() % ([UPPER_LIMIT] - [LOWER_LIMIT])) + [LOWER_LIMIT]
Here is a specific example:
Example - Generate pseudo random numbers in the range of 40 to 99:
This will generate a random number within a range of 40 and 99.
If you want to generate random numbers in range including '0' , use the following while 'max' is the maximum number in the range.
There is no such method as
java.util.Random.getRandomDigits
.To get a random number use nextInt:
Also you should create the random object once when your application starts:
You should not create a new random object every time you want a new random number. Doing this destroys the randomness.
For example, let's say that you want to create a random number between 50 and 60, you can use one of the following methods.
new Random().nextInt()%6 returns a value between -5 and 5. and when you add it to 55 you can get values between 50 and 60
Second method:
Math.abs(new Random().nextInt()%11) creates a value between 0 and 10. Later you can add 50 which in the will give you a value between 50 and 60
Generally, I find RandomUtils (from Apache commons lang) an easier way to generate random numbers than
java.util.Random