Random Integer Generation

Random Integer Generation

How do I write a Java program that generates random numbers withinlimits, such as 1 to 100, or 1 to 1000?

The java.util package includes a Random class which will generate asequence of pseudo-random numbers. Pseudo-random number sequencesappear to have a random distribution, but have a definite order.Given the same seed, a pseudo-random number generator will alwaysproduce the same sequence of numbers. Therefore, you shouldinitialize the Random class with as random a seed as possible. Usingthe current time as a seed is often sufficient.

However, when apseudo-random number sequence is exhausted, it wraps around and startsagain from the beginning. Consequently, for long-lived applicationsthat generate many random numbers over time, you will want toperiodically reseed your random generator.

The Random class does not provide a generic means of generating randomintegers within a specific range. Rather, it generates a uniformlydistributed set of values between 0 and some upper bound. For doublesand floats it generates a value between 0 and 1. You can use this togenerate arbitrary ranges of random integers. The following exampleprogram provides a random integer generating class that takes care ofconverting a random double into a random integer within a specificrange. It also takes care of reseeding the random number generatorafter the sequence has been in use for a long time.

import java.util.*;public final class RandomIntGenerator {  public static final int DEFAULT_MIN_RANGE = 1;  public static final int DEFAULT_MAX_RANGE = 100;  int _minRange, _maxRange, _range;  long _numCalls;  Random _random;  public RandomIntGenerator() {    this(DEFAULT_MIN_RANGE, DEFAULT_MAX_RANGE);  }  public RandomIntGenerator(int minRange, int maxRange) {    _random   = new Random(System.currentTimeMillis());    setRange(minRange, maxRange);    _numCalls = 0;  }  public void setRange(int minRange, int maxRange) {    _minRange = minRange;    _maxRange = maxRange;    _range    = maxRange - minRange + 1;  }  public int nextInt() {    double d;    d = ((double)_range)*_random.nextDouble();        if(++_numCalls == Integer.MAX_VALUE) {      // The pseudo-random number sequence is sufficiently      // exhausted that it is time to switch to a new seed.      _numCalls = 0;      _random.setSeed(System.currentTimeMillis());    }    return (_minRange + (int)d);  }  public static final void main(String[] args) {    RandomIntGenerator randomInt;    randomInt = new RandomIntGenerator();    for(int i = RandomIntGenerator.DEFAULT_MIN_RANGE;        i 


Share the Post: