forum

Home / DeveloperSection / Forums / Generating random integers in a range with Java

Generating random integers in a range with Java

Samuel Fernandes168204-May-2015
I am trying to generate a random integer 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 integer value in the range of 0 (inclusive) and n (exclusive). I couldn't find a method, which returns a random integer 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 is assinged values numbers bigger than maximum.

Solution 2:

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

How do I solve this problem?


Updated on 05-May-2015

Can you answer this question?


Answer

1 Answers

Liked By