Choosing Random number in java

时间:2016-10-20 19:25:55

标签: java

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?

1 个答案:

答案 0 :(得分: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
--------------------------------+------------------+-------------------
相关问题