Home > DeveloperSection > Forums > Generating random integers in a range with Java
Samuel Fernandes
Samuel Fernandes

Total Post:154

Points:1082
Posted on    May-04-2015 11:45 PM

 Java Java 
Ratings:


 1 Reply(s)
 476  View(s)
Rate this:
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?



Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    May-05-2015 12:40 AM

The standard way to do this is as follows:

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {
    // NOTE: Usually this should be a field rather than a method
    // variable so that it is not re-seeded every call.
    Random rand = new Random();
    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}
See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

Don't want to miss updates? Please click the below button!

Follow MindStick