Possible Duplicate:
Java: generating random number in a range
How do I generate a random value between two numbers. Random.nextInt() gives you between 0 and the passed value. How do I generate a value between minValue and a maxValue
Write a method like:
public static int getRandom(int from, int to) {
if (from < to)
return from + new Random().nextInt(Math.abs(to - from));
return from - new Random().nextInt(Math.abs(to - from));
}
This also takes account for facts, that nextInt()
argument must be positive, and that from can be bigger then to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With