Java: Random long value in an interval

Mintz picture Mintz · Dec 5, 2012 · Viewed 23.2k times · Source

Possible Duplicate:
Java: random long number in 0 <= x < n range

I want to generate a random long value in an interval but it seems that the Random class nextLong() doesn't accept arguments like nextInt(). What can I do here?

Answer

Yogendra Singh picture Yogendra Singh · Dec 5, 2012

If you want range based long values then do the below:

 long LOWER_RANGE = 0; //assign lower range value
 long UPPER_RANGE = 1000000; //assign upper range value
 Random random = new Random();


 long randomValue = LOWER_RANGE + 
                           (long)(random.nextDouble()*(UPPER_RANGE - LOWER_RANGE));