Is there an Equivalent of .Net framework's Random.Next(Int32, Int32) in the Java API?
Question
I am working on porting an existing VB.Net application to Java, and could not find an equivalent to Random.Next(Int32, Int32).
I could find only java.util.Random.next(int val)
in the Java API.
Is there an Equivalent of .Net framework's Random.Next(Int32, Int32) in the Java API?
Solution
As Marc says, just adapt Random.nextInt(int)
, with a couple of sanity checks:
public static int nextInt(Random rng, int lower, int upper) {
if (upper < lower) {
throw new IllegalArgumentException();
}
if ((long) upper - lower > Integer.MAX_VALUE) {
throw new IllegalArgumentException();
}
return rng.nextInt(upper-lower) + lower;
}
OTHER TIPS
no but you can have it this way:
public static int randomInRange(int min, int max){
return min+Random.next(max-min);
}
Consider RandomUtils from Apache Commons Lang:
http://commons.apache.org/lang/apidocs/org/apache/commons/lang/math/RandomUtils.html
Well, you can use Random.nextInt(int) specifying the range, and then just add the minimum value? i.e. rand.nextInt(12) + 5
Call to Random.Next(x, y)
can be translated to something like Random.nextInt(y - x) + x;