Alex Rivera | Logout

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

Asked 2010-03-30T14:41:21.397
162

Random class has a method to generate random int in a given range. For example:

Random r = new Random(); 
int x = r.nextInt(100);

This would generate an int number more or equal to 0 and less than 100. I'd like to do exactly the same with long number.

long y = magicRandomLongGenerator(100);

Random class has only nextLong(), but it doesn't allow to set range.

Edit
Report

1 Answer

0

The methods using the r.nextDouble() should use:

long number = (long) (rand.nextDouble()*max);


long number = x+(((long)r.nextDouble())*(y-x));
answered 2012-04-08T12:18:57.530

Your Answer