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`.
To generate a random number "in between two numbers", use the following code:
This gives you a random number in between 1 (inclusive) and 11 (exclusive), so initialize the upperBound value by adding 1. For example, if you want to generate random number between 1 to 10 then initialize the upperBound number with 11 instead of 10.
I use this:
You can cast it to an Integer if you want.
Here's a helpful class to generate random
ints
in a range with any combination of inclusive/exclusive bounds:Here is a simple sample that shows how to generate random number from closed
[min, max]
range, whilemin <= max is true
You can reuse it as field in hole class, also having all
Random.class
methods in one placeResults example:
Sources:
ThreadLocalRandom equivalent of class java.util.Random for multithreaded environment. Generating a random number is carried out locally in each of the threads. So we have a better performance by reducing the conflicts.
x,y - intervals e.g. (1,10)