#### Generating random integers in a range with Java

Total Post:159

Points:1117
1230  View(s)
Ratings:
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?

1. Post:397

Points:3117
##### Re: Generating random integers in a range with Java

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.

#### CONTACT INFO

10-B Taskand Marg, Near Patrika Chauraha, Civil Lines, Prayagraj, UP, India-211001.
contact@mindstick.com
91-532-2400505

969-G Edgewater Blvd,Suite
793 Foster City-94404, CA (USA)
+1-650-242-0133