views:

140

answers:

6

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?

  • Thanks,
A: 

Well, you can use Random.nextInt(int) specifying the range, and then just add the minimum value? i.e. rand.nextInt(12) + 5

Marc Gravell
rand.nextInt(max) + min is wrong; this returns integers greater than max?
dfa
Which is why I used the word **range**, not max
Marc Gravell
+2  A: 

no but you can have it this way:

public static int randomInRange(int min, int max){
      return min+Random.next(max-min);
}
MahdeTo
+2  A: 

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;
}
Jon Skeet
why is this necessary ? if ((long) upper - lower > Integer.MAX_VALUE) { throw new IllegalArgumentException(); }
MahdeTo
Thanks Jon,This might work out for me.
Murali
@MahdeTo: Consider nextInt(rng, Integer.MIN_VALUE, Integer.MAX_VALUE)
Jon Skeet
(In particular, think about what would happen in the call to rng.nextInt...)
Jon Skeet
A: 

Call to Random.Next(x, y) can be translated to something like Random.nextInt(y - x) + x;

Anton Gogolev
+1  A: 

Consider RandomUtils from Apache Commons Lang:

http://commons.apache.org/lang/apidocs/org/apache/commons/lang/math/RandomUtils.html

Benedikt Eger
A: 

Not a built-in function, but it's easy enough to do. See the correct answer listed here.

duffymo