如何在特定范围内生成随机int值?

以下方法存在与整数溢出相关的错误:

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`.

当前回答

Random random = new Random();
int max = 10;
int min = 3;
int randomNum = random.nextInt(max) % (max - min + 1) + min;

其他回答

使用nexttint(n)方法为最小值和最大值的差值生成一个随机数,然后将最小值添加到结果中:

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

您可以按以下方式操作。

import java.util.Random;
public class RandomTestClass {

    public static void main(String[] args) {
        Random r = new Random();
        int max, min;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter maximum value : ");
        max = scanner.nextInt();
        System.out.println("Enter minimum value : ");
        min = scanner.nextInt();
        int randomNum;
        randomNum = r.nextInt(max) + min;
        System.out.println("Random Number : " + randomNum);
    }

}

请原谅我过于挑剔,但大多数人建议的解决方案,即min+rng.nextInt(max-min+1),似乎很危险,因为:

rng.nextInt(n)无法达到整数.MAX_VALUE。当min为负值时,(max-min)可能会导致溢出。

万无一失的解决方案将为[Integer.min_VALUE,Integer.max_VALUE]内的任何min<=max返回正确的结果。请考虑以下简单的实现:

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;
}

尽管效率低下,但请注意while循环中成功的概率始终为50%或更高。

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;
    }
}
int randomNum = 5 + (int)(Math.random()*5);

范围5-10