Java random integer in min and max range

From JavaWiki.org
Revision as of 17:30, 4 March 2016 by Javawiki (talk | contribs) (Created page with "Following sample code returns a random integer within the give min and max range (both inclusive) <syntaxhighlight lang="java"> import java.util.Random; public class Random...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Following sample code returns a random integer within the give min and max range (both inclusive)

	
import java.util.Random;

public class RandomRange {
    // Declare as class variable so that it is not re-seeded every call
    private static Random random = new Random();

    /**
     * Returns a psuedo-random number between Min and Max (both inclusive)
     * @param min Minimim value
     * @param max Maximim value. Must be greater than min.
     * @return Integer between min and max (both inclusive)
     * @see java.util.Random#nextInt(int)
     */
    public static int nextInt(int min, int max) {
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        return random.nextInt((max - min) + 1) + min;
    }
}