Is there an Equivalent of .Net framework's Random.Next(Int32, Int32) in the Java API?

StackOverflow https://stackoverflow.com/questions/839073

  •  22-07-2019
  •  | 
  •  

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?

Was it helpful?

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);
}

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;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top