How To - Generate A Random Integer Within a Range


Advertisements

Description:

These are a few ways to generate a random integer within a range, however this is the most efficient way.

Using Random Class

Here is the code for this method:

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * Integer.MAX_VALUE - 1.
 *
 * @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 randomizer = new Random();

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNumber = randomizer.nextInt((max - min) + 1) + min;

    return randomNumber;
}

java_strings.htm

Advertisements