how to set range for math random java code example
Example 1: random number in range java
(int)(Math.random() * ((max - min) + 1)) + min
Copy
Example 2: how to get random number in java in range
private static int getRandomNumberInRange(int min, int max)
{
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
new Random().nextInt(5);
new Random().nextInt(6);
new Random().nextInt(7);
new Random().nextInt(8);
new Random().nextInt(9);
new Random().nextInt(10);
new Random().nextInt(11);
new Random().nextInt(5 + 1)
new Random().nextInt(6 + 1)
new Random().nextInt(7 + 1)
new Random().nextInt(8 + 1)
new Random().nextInt(9 + 1)
new Random().nextInt(10 + 1)
new Random().nextInt(11 + 1)
new Random().nextInt(5 + 1) + 10
new Random().nextInt(6 + 1) + 10
new Random().nextInt(7 + 1) + 10
new Random().nextInt(8 + 1) + 10
new Random().nextInt(9 + 1) + 10
new Random().nextInt(10 + 1) + 10
new Random().nextInt(11 + 1) + 10
new Random().nextInt((max - min) + 1) + min
new Random().nextInt((30 - 10) + 1) + 10
new Random().nextInt((20) + 1) + 10
new Random().nextInt(21) + 10
new Random().nextInt((max - min) + 1) + min
new Random().nextInt((99 - 15) + 1) + 15
new Random().nextInt((84) + 1) + 15
new Random().nextInt(85) + 15
Example 3: random int in range java
import java.util.concurrent.ThreadLocalRandom;
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);