How to generate a random number between two numbers in Java? [duplicate]
this question already has answers here :
generate random data within a range
(3 responses)
Closed for 4 years.
How does it generate a random number in specific java between min and max? Because with the nextInt function of the Random Class you can only specify the max.
0
Author: Vinicius Fernandes, 2016-09-29
1 answers
You can use the Random
in this way
public int numeroAleatorio(int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Or use the Class Math
public int numeroAleatorio(int min, int max){
int randomNum = min + (int)(Math.random() * (max - min));
return randomNum;
}
3
Author: LINQ, 2016-09-29 22:44:43