Advertise with us

Generating random number in a range with Java

Hi Everyone!

I am trying to generate a random number with Java, but random in a specific range. For example, my range is 5-10, meaning that 5 is the smallest possible value the 

random number can take, and 10 is the biggest. Any other number in between these numbers is possible to be a value, too.

In Java, there is a method random() in the Math class, which returns a double value between 0.0 and 1.0. In the class Random there is a method nextInt(int n), which 

returns a random value in the range of 0 (inclusive) and n (exclusive). I couldn't find a method, which returns a random value between two numbers.

I have tried the following things, but I still have problems: (minimum and maximum are the smallest and biggest numbers).

Solution 1 :

randomNum = minimum + (int)(Math.random()*maximum); 
problem: randomNum takes is assinged values numbers bigger that maximum

Solution 2 :

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
problem: randomNum takes is assigned values smaller than minimum.

Could you suggest how to solve my problem, or point me to some references?

Thanks in advance!
Last updated:5/7/2013 7:48:49 AM

1 Answers


Hi Chinto!

this is what i do:-
I just generate a random number using Math.random() and multiply it by a big number...lets say 10000.
So, i get a number between 0 to 10,000 and call this number i.
Now, If i need numbers between (x, y), then do the following:

i = x + (i % (y - x));
So, all i are numbers between x and y.

EDIT: To remove the bias as pointed out in the comments, rather than multiplying it by 10000 (or the big number), multiply it by (y-x)