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?
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?
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
--------------------------------+------------------+-------------------