0

How to Get Random Number Between Given Range in Java if minimum is more than 1? for example if i want to get random number between 6 to 20. currently i am using this code

Random rand = new Random(); 
int  rnd = rand.nextInt(499) + 1;

it is working well, but if i change 1 to some high number for example 6, it will not work properly, i want to get random number that is between 6 and 20. is it possible using above function ?

Shumaila
  • 41
  • 6

1 Answers1

2

Simply calculate a random number between 0 and 14, than add 6

Random rand = new Random(); 
int  rnd = rand.nextInt(14) + 6;
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • Nice Trick. it means Java do not have proper function to get random between given range, and we have to use some trick to get this...? – Shumaila Jan 26 '16 at 14:42
  • 1
    Exactly, basically any range can be seen as a range from 0 to to size of range plus the distance from 0 of minimum value – Davide Lorenzo MARINO Jan 26 '16 at 14:44