¿Cómo puedo generar enteros aleatorios dentro de un rango específico en Java?

¿Cómo puedo generar un valor int aleatorio en un rango específico?

He probado lo siguiente, pero no funciona:

Intento 1:

randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.

Intento 2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.

En Java 1.7 o posterior, la forma estándar de hacerlo es la siguiente:

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

Véase el JavaDoc correspondiente. Este enfoque tiene la ventaja de no tener que inicializar explícitamente una instancia java.util.Random, que puede ser una fuente de confusión y error si se utiliza de forma inapropiada.

Sin embargo, a la inversa, no hay forma de establecer explícitamente la semilla, por lo que puede ser difícil reproducir los resultados en situaciones en las que eso es útil, como las pruebas o el guardado de estados del juego o similares. En esas situaciones, se puede utilizar la técnica anterior a Java 1.7 que se muestra a continuación.

Antes de Java 1.7, la forma estándar de hacer esto es la siguiente:

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: This will (intentionally) not run as written so that folks
    // copy-pasting have to think about how to initialize their
    // Random instance.  Initialization of the Random instance is outside
    // the main scope of the question, but some decent options are to have
    // a field that is initialized once and then re-used as needed or to
    // use ThreadLocalRandom (if using at least Java 1.7).
    // 
    // In particular, do NOT do 'Random rand = new Random()' here or you
    // will get not very good / not very random results.
    Random rand;

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

Véase el JavaDoc correspondiente. En la práctica, la clase java.util.Random suele ser preferible a java.lang.Math.random().

En particular, no hay necesidad de reinventar la rueda de generación de enteros aleatorios cuando hay una API directa dentro de la biblioteca estándar para realizar la tarea.

Comentarios (18)

Utilizar:

minimum + rn.nextInt(maxValue - minvalue + 1)
Comentarios (0)
 rand.nextInt((max+1) - min) + min;
Comentarios (0)