Como gerar um inteiro aleatório entre min e max em java?

que método devolve um int aleatório entre um min e o máximo? Ou não existe tal método?

O que procuro é algo parecido com isto.
NAMEOFMETHOD (min, max) 

(em que os min e os max são int s)

que devolve algo assim:

8

(aleatoriamente)

Se esse método existir, pode por favor ligar-se à documentação relevante com a sua resposta. Obrigado.

actualização: tentar implementar a solução completa na resposta nextInt tenho isto:

class TestR
{
    public static void main (String[]arg) 
    {   
        Random random = new Random() ;
        int randomNumber = random.nextInt(5) + 2;
        System.out.println (randomNumber) ; 
    } 
} 
Ainda estou a receber os mesmos erros do complier.
TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
        ^
TestR.java:5: cannot find symbol
symbol  : class Random
location: class TestR
        Random random = new Random() ;
                            ^
TestR.java:6: operator + cannot be applied to Random.nextInt,int
        int randomNumber = random.nextInt(5) + 2;
                                         ^
TestR.java:6: incompatible types
found   : <nulltype>
required: int
        int randomNumber = random.nextInt(5) + 2;
                                             ^
4 errors
O que se passa aqui?

 33
Author: Santosh Kumar, 2010-03-15

7 answers

Construir um objecto Aleatório no arranque da aplicação:

Random random = new Random();

Então use aleatoriamente.nextInt (int):

int randomNumber = random.nextInt(max + 1 - min) + min;

Note que os limites inferior e superior são inclusivos.

 114
Author: Mark Byers, 2017-02-05 18:01:33

Pode usar aleatoriamente.nextInt (n). Isto devolve um int Aleatório em [0, n). Apenas usando max-min+1 no lugar de n e adicionando min para a resposta dará um valor na gama desejada.

 16
Author: MAK, 2010-03-14 22:26:04
public static int random_int(int Min, int Max)
{
     return (int) (Math.random()*(Max-Min))+Min;
}

random_int(5, 9); // For example
 5
Author: Jupiter Kasparov, 2014-06-30 11:45:41

Como as soluções acima não consideram o possível excesso de fazer max-min Quando min é negativo, aqui outra solução (semelhante à de kerouac)

public static int getRandom(int min, int max) {

        if (min > max) {
            throw new IllegalArgumentException("Min " + min + " greater than max " + max);
        }

        return (int) ( (long) min + Math.random() * ((long)max - min + 1));
    }

Isto funciona mesmo que lhe ligues com:

getRandom(Integer.MIN_VALUE, Integer.MAX_VALUE) 
 4
Author: arcuri82, 2016-12-05 22:46:27

Usar a classe Aleatória é o caminho a seguir como sugerido na resposta aceite, mas aqui está uma forma menos directa e correcta de o fazer se não quiser criar um novo objecto Aleatório:

min + (int) (Math.random() * (max - min + 1));
 0
Author: kerouac, 2016-09-13 18:26:19

Isto gera um número inteiro aleatório de tamanho psize

public static Integer getRandom(Integer pSize) {

    if(pSize<=0) {
        return null;
    }
    Double min_d = Math.pow(10, pSize.doubleValue()-1D);
    Double max_d = (Math.pow(10, (pSize).doubleValue()))-1D;
    int min = min_d.intValue();
    int max = max_d.intValue();
    return RAND.nextInt(max-min) + min;
}
 -2
Author: julius.kabugu, 2012-01-16 14:53:43

Importar java.util.Aleatório;

 -5
Author: darlinton, 2010-03-14 23:34:22