How do I generate a random int
value in a specific range?
I have tried the following, but those do not work:
Attempt 1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Attempt 2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
Use:
I wonder if any of the random number generating methods provided by an Apache Commons Math library would fit the bill.
For example:
RandomDataGenerator.nextInt
orRandomDataGenerator.nextLong
In case of rolling a dice it would be random number between 1 to 6 (not 0 to 6), so:
I found this example Generate random numbers :
This example generates random integers in a specific range.
An example run of this class :
Let us take an example.
Suppose I wish to generate a number between 5-10:
Let us understand this...