Como posso gerar inteiros aleatórios dentro de um intervalo específico em Java?

Como posso gerar um valor aleatório de int em um intervalo específico?

Eu tentei o seguinte, mas esses não funcionam:

Tenta 1:

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

Attempt 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`.

Em **Java 1.7 ou posterior***, a forma padrão de fazer isso é a seguinte:

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

Ver o JavaDoc relevante. Esta abordagem tem a vantagem de não precisar inicializar explicitamente uma instância java.util.Random, que pode ser uma fonte de confusão e erro se usada de forma inadequada.

No entanto, por outro lado, não há como definir explicitamente a semente, pelo que pode ser difícil reproduzir resultados em situações em que isso seja útil, tais como testar ou salvar estados de jogo ou similares. Nessas situações, a técnica pré-Java 1.7 mostrada abaixo pode ser usada.

Antes de Java 1.7, a forma padrão de fazer isso é a seguinte:

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

Ver o JavaDoc relevante. Na prática, a classe java.util.Random é frequentemente preferível a java.lang.Math.random().

Em particular, não há necessidade de reinventar a roda de geração de números inteiros aleatórios quando há uma API direta dentro da biblioteca padrão para realizar a tarefa.

Comentários (18)

Use:

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