¿Existe un equivalente de Random.Next (Int32, Int32) de .Net framework en la API de Java?
Pregunta
Estoy trabajando en portar una aplicación VB.Net existente a Java, y no pude encontrar un equivalente a Random.Next (Int32, Int32).
Solo pude encontrar java.util.Random.next (int val)
en la API de Java.
¿Existe un equivalente de Random.Next (Int32, Int32) de .Net framework en la API de Java?
Solución
Como dice Marc, simplemente adapte Random.nextInt (int)
, con un par de comprobaciones de cordura:
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;
}
Otros consejos
no, pero puedes tenerlo de esta manera:
public static int randomInRange(int min, int max){
return min+Random.next(max-min);
}
Considere RandomUtils de Apache Commons Lang:
Bueno, puede usar Random.nextInt (int) especificando el rango, y luego simplemente agrega el valor mínimo? es decir, rand.nextInt (12) + 5
Llamar a Random.Next (x, y)
se puede traducir a algo como Random.nextInt (y - x) + x;