Is it possible to generate a random number between two numbers in Java? [duplicate]

0

How do you generate a random number in the specified java between min and max? Because with the nextInt function of the Random class you can only specify the max.

    
asked by anonymous 30.09.2016 / 00:37

1 answer

3

You can use Random 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;
}
    
30.09.2016 / 00:39