如何在特定范围内生成随机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`.

当前回答

如果你不想重新发明轮子,这里有一个简单明了的解决方案:

RandomStringUtils.randomNumeric(count); // Where count is the number of digits you want in the random number.

Apache Commons,例如组件Lang中的RandomUtils,提供了许多选项来生成任意格式的随机数。

其他回答

Use:

minValue + rn.nextInt(maxValue - minValue + 1)

如果您已经使用Commons Lang API 3.x或最新版本,那么有一个类用于随机数生成RandomUtils。

public static int nextInt(int startInclusive, int endExclusive)

返回指定范围内的随机整数。

参数:

startInclusive-指定的起始值

endExclusive-指定的结束值

int random = RandomUtils.nextInt(999,1000000);

注:在RandomUtils中,有许多生成随机数的方法

在Java 1.7或更高版本中,执行此操作的标准方法如下:

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

请参阅相关的JavaDoc。这种方法的优点是不需要显式初始化java.util.Random实例,如果使用不当,可能会导致混淆和错误。

然而,相反,没有办法明确设置种子,因此在测试或保存游戏状态等有用的情况下,很难再现结果。在这些情况下,可以使用下面所示的Java 1.7之前的技术。

在Java 1.7之前,执行此操作的标准方法如下:

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: This will (intentionally) not run as written so that folks
    // copy-pasting have to think about how to initialize their
    // Random instance.  Initialization of the Random instance is outside
    // the main scope of the question, but some decent options are to have
    // a field that is initialized once and then re-used as needed or to
    // use ThreadLocalRandom (if using at least Java 1.7).
    // 
    // In particular, do NOT do 'Random rand = new Random()' here or you
    // will get not very good / not very random results.
    Random rand;

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

请参阅相关的JavaDoc。实际上,java.util.Random类通常比java.lang.Math.Random()更好。

特别是,当标准库中有一个简单的API来完成任务时,无需重新发明随机整数生成轮。

您可以使用以下方法来执行此操作:

int range = 10;
int min = 5
Random r = new Random();
int = r.nextInt(range) + min;

我将简单地说明问题提供的解决方案有什么问题,以及错误的原因。

解决方案1:

randomNum = minimum + (int)(Math.random()*maximum); 

问题:randomNum分配的值大于最大值。

解释:假设我们的最小值是5,而你的最大值是10。Math.random()中任何大于0.6的值都将使表达式的计算结果为6或更大,加上5将使其大于10(最大值)。问题是你将随机数乘以最大值(这会产生一个几乎和最大值一样大的数字),然后再加上最小值。除非最小值是1,否则它是不正确的。如其他答案所述,您必须切换到

randomNum = minimum + (int)(Math.random()*(maximum-minimum+1))

+1是因为Math.random()永远不会返回1.0。

解决方案2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;

这里的问题是,如果第一项小于0,“%”可能会返回负数。由于rn.nextInt()以约50%的概率返回负值,因此也不会得到预期的结果。

然而,这几乎是完美的。您只需进一步查看Javadoc,nextInt(int n)。使用该方法

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

也将返回所需的结果。