Generate Random Number Inclusive and Exclusive in Java
Random numbers can be generated using the java.util.Random
class or Math.random()
static method. There is no need to reinvent the random integer generation when there is a useful API within the standard Java JDK. Unless you really really care for performance then you can probably write your own amazingly super fast generator. In this tutorial I’ve chosen for the java.util.Random class because I find it more readable witch results in cleaner and more understandable code. Remember you write it once and you or someone else will read it many many many times.
package com.memorynotfound.random;
import java.util.Random;
/**
* Generates random values between min and max taking into account with inclusive and exclusive values
* @author memorynotfound.com
*/
public class RandomRange {
private static Random rnd = new Random();
public static int nextIncInc(int min, int max) {
return rnd.nextInt(max - min + 1) + min;
}
public static int nextIncExc(int min, int max) {
return rnd.nextInt(max - min) + min;
}
public static int nextExcInc(int min, int max) {
return rnd.nextInt(max - min) + 1 + min;
}
public static int nextExcExc(int min, int max) {
return rnd.nextInt(max - min - 1) + 1 + min;
}
}
Example Random numbers Explained
Inclusive Minimum and Inclusive Maximum
Generates a random number between min (inclusive) and max (inclusive)
public static int nextIncInc(int min, int max) {
return rnd.nextInt(max - min + 1) + min;
}
Inclusive Minimum and Exclusive Maximum
Generates a random number between min (inclusive) and max (exclusive)
public static int nextIncExc(int min, int max) {
return rnd.nextInt(max - min) + min;
}
Exclusive Minimum and Inclusive Maximum
Generates a random number between min (exclusive) and max (inclusive)
public static int nextExcInc(int min, int max) {
return rnd.nextInt(max - min) + 1 + min;
}
Exclusive Minumum and Maximum Exclusive
Generates a random number between min (exclusive) and max (exclusive)
public static int nextExcExc(int min, int max) {
return rnd.nextInt(max - min - 1) + 1 + min;
}
References
You can read more over the previous example at these links.