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?
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.
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.
public static int random_int(int Min, int Max)
{
return (int) (Math.random()*(Max-Min))+Min;
}
random_int(5, 9); // For example
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)
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));
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;
}
Importar java.util.Aleatório;