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

我尝试了以下,但那些不起作用:

尝试1:

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

尝试2:

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

答案

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

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

查看相关的JavaDoc。这种方法具有无需显式初始化java.util.Random实例的优点,如果使用不当,可能会造成混淆和错误。

但是,相反,无法明确设置种子,因此在测试或保存游戏状态或类似情况时很难重现结果。在这些情况下,可以使用下面所示的Java 1.7之前的技术。

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

importjava.util.Random;
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* Integer.MAX_VALUE - 1.
*
* @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 intrandInt(intmin, intmax) {
// 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.
Randomrand;
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
intrandomNum=rand.nextInt((max-min) + 1) +min;
returnrandomNum;
}

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

完成这个的一个标准模式是:

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

该爪哇数学库函数的Math.random()生成的范围内的双值[0,1)。注意这个范围不包括1。

为了首先获得特定范围的值,您需要乘以您想要覆盖的值范围的大小。

Math.random() * ( Max - Min )

这会返回范围中的一个值[0,Max-Min),其中不包括“Max-Min”。

例如,如果你愿意[5,10],你需要覆盖五个整数值,以便你使用

Math.random() * 5

这将返回范围内的值[0,5),其中不包括5。

现在您需要将此范围调整到您定位的范围。您可以通过添加最小值来完成此操作。

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

您现在将获得该范围内的值[Min,Max)。按照我们的例子,这意味着[5,10):

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

但是,这仍然不包括Max,你会得到双重价值。为了获得Max包含的值,需要在范围参数中加1 (Max - Min),然后通过强制转换为整数来截断小数部分。这通过以下方式完成:

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

在那里你有它。范围内的随机整数值[Min,Max]或每个示例[5,10]:

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

例如,如果您想在[0,10]范围内生成五个随机整数(或一个整数),请执行以下操作:

Randomr= new Random();
int[]fiveRandomNumbers=r.ints(5, 0, 11).toArray();
intrandomNumber=r.ints(1, 0, 11).findFirst().getAsInt();

第一个参数表示IntStream生成的大小(这是产生无限制的方法的重载方法IntStream)。

如果你需要做多个独立的调用,你可以从流中创建一个无限的基本迭代器:

public final class IntRandomNumberGenerator {
private PrimitiveIterator.OfIntrandomIterator;
/**
* Initialize a new random number generator that generates
* random numbers in the range [min, max]
* @param min - the min value (inclusive)
* @param max - the max value (inclusive)
*/
public IntRandomNumberGenerator(intmin, intmax) {randomIterator= new Random().ints(min,max+ 1).iterator();
}
/**
* Returns a random number in the range (min, max)
* @return a random number in the range (min, max)
*/
public intnextInt() {
returnrandomIterator.nextInt();
}
}

你也可以做double和long价值。