# 如何在Java中的特定範圍內生成隨機整數？

``````Min + (int)(Math.random() * ((Max - Min) + 1))
``````

Java Math庫函數Math.random（）在`[0,1)`範圍內生成一個double值。 注意這個範圍不包括1。

``````Math.random() * ( Max - Min )
``````

``````Math.random() * 5
``````

``````Min + (Math.random() * (Max - Min))
``````

``````5 + (Math.random() * (10 - 5))
``````

``````Min + (int)(Math.random() * ((Max - Min) + 1))
``````

``````5 + (int)(Math.random() * ((10 - 5) + 1))
``````
Question

``````randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
``````

``````Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
``````

``````int rand = ThreadLocalRandom.current().nextInt(x,y);
``````

x，y - 間隔例如（1,10）

``````public static Random RANDOM = new Random(System.nanoTime());

public static final float random(final float pMin, final float pMax) {
return pMin + RANDOM.nextFloat() * (pMax - pMin);
}
``````

``````Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);
``````

``````public static int generateRandomInteger(int min, int max) {
SecureRandom rand = new SecureRandom();
rand.setSeed(new Date().getTime());
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
``````

``````public static int getRandomNumberBetween(int min, int max) {
Random foo = new Random();
int randomNumber = foo.nextInt(max - min) + min;
if (randomNumber == min) {
// Since the random number is between the min and max values, simply add 1
return min + 1;
} else {
return randomNumber;
}
}
``````

``````public static int getRandomNumberFrom(int min, int max) {
Random foo = new Random();
int randomNumber = foo.nextInt((max + 1) - min) + min;

return randomNumber;
}
``````

``````rand.nextInt((max+1) - min) + min;
``````

`````` rand.nextInt((max+1) - min) + min;
``````

``````import java.util.Random;

public class RandomUtil {
// 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;
}
}
``````

``````Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;
``````

``````Random random = new Random();

int max = 10;
int min = 5;
int totalNumber = 10;

IntStream stream = random.ints(totalNumber, min, max);
stream.forEach(System.out::println);
``````

``````Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
``````

``````minimum + rn.nextInt(maxValue - minvalue + 1)
``````

• `rng.nextInt(n)`無法達到`Integer.MAX_VALUE`
• `(max - min)`可能會在`min`為負時導致溢出。

``````int nextIntInRange(int min, int max, Random rng) {
if (min > max) {
throw new IllegalArgumentException("Cannot draw random int from invalid range [" + min + ", " + max + "].");
}
int diff = max - min;
if (diff >= 0 && diff != Integer.MAX_VALUE) {
return (min + rng.nextInt(diff + 1));
}
int i;
do {
i = rng.nextInt();
} while (i < min || i > max);
return i;
}
``````

``````int random = minimum + Double.valueOf(Math.random()*(maximum-minimun)).intValue();
``````