0
Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

I've tried it and it is working but still confuse about the logic used, I want to know that why we add min value to random number in end?

Pshemo
  • 113,402
  • 22
  • 170
  • 242

1 Answers1

1

Random#nextInt(n) returns a random integer between 0 and n-1. By adding min to the return value of r.nextInt(max - min + 1), the result is a random integer between min and max (inclusive).

The following table might clarify the logic a bit:

     Expression                 |  smallest value  |  largest value
--------------------------------+------------------+-------------------
r.nextInt(max - min + 1)        |       0          |    max - min
--------------------------------+------------------+-------------------
r.nextInt(max - min + 1) + min  |      min         |       max
--------------------------------+------------------+-------------------
Ted Hopp
  • 222,293
  • 47
  • 371
  • 489