Is there any way to generate a random number between two numbers in Java?

Asked

Viewed 6,742 times

0

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

1 answer

3


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

    And this logic there, has how to explain it? I found interesting this way, but did not understand its functioning.

  • 1

    I’m just providing that, @diegofm

  • Thanks @jbueno, just move the final result by adding min. Now there is some difference in performance between these two classes?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.