-3

I have seen a lot of different ways to generate random numbers in between a certain range. Just today I came across the following piece of code. but upon doing research, I did not see anybody describe it this way.

Random ran = new Random();
int j = ran.nextInt(5+10);

My question is, does the code above assign a random integer to j between the numbers of 5 and 10? If so, what if you wrote the second line of code like this int j = rgen.nextInt(10+5);

Omar N
  • 1,720
  • 2
  • 21
  • 33

1 Answers1

3

To generate a random int within [min, max[:

Random r = new Random();
int number = r.nextInt(max - min) + min;

So in your case:

int j = r.nextInt(10 - 5) + 5;
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • Thank you for the help! This helps clarify it. Last question, why do you add the min value outside the bracket? – Omar N Nov 21 '15 at 18:21