如何在 Java 中生成特定范围内的随机整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/363681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 13:51:25  来源:igfitidea点击:

How do I generate random integers within a specific range in Java?

javarandominteger

提问by user42155

How do I generate a random intvalue in a specific range?

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

I have tried the following, but those do not work:

我尝试了以下方法,但这些方法不起作用:

Attempt 1:

尝试 1:

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

Attempt 2:

尝试 2:

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

回答by krosenvold

Use:

用:

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

回答by Greg Case

In Java 1.7 or later, the standard way to do this is as follows:

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

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Randominstance, which can be a source of confusion and error if used inappropriately.

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

However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.

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

Before Java 1.7, the standard way to do this is as follows:

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

See the relevant JavaDoc. In practice, the java.util.Randomclass is often preferable to java.lang.Math.random().

请参阅相关的 JavaDoc。在实践中,java.util.Random类通常比java.lang.Math.random()更可取。

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

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

回答by Michael Myers

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

回答by Chinnery

I wonder if any of the random number generating methods provided by an Apache Commons Mathlibrary would fit the bill.

我想知道Apache Commons Math库提供的任何随机数生成方法是否符合要求。

For example: RandomDataGenerator.nextIntor RandomDataGenerator.nextLong

例如:RandomDataGenerator.nextIntRandomDataGenerator.nextLong

回答by user2427

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

Or take a look to RandomUtils from Apache Commons.

或者看看Apache Commons 的RandomUtils 。

回答by Bill the Lizard

You can edit your second code example to:

您可以将第二个代码示例编辑为:

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

回答by TJ_Fischer

Note that this approach is more biased and less efficient than a nextIntapproach, https://stackoverflow.com/a/738651/360211

请注意,这种方法比一种nextInt方法更偏向且效率更低,https://stackoverflow.com/a/738651/360211

One standard pattern for accomplishing this is:

实现此目的的一种标准模式是:

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

The JavaMath library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.

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

In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.

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

Math.random() * ( Max - Min )

This returns a value in the range [0,Max-Min), where 'Max-Min' is not included.

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

For example, if you want [5,10), you need to cover five integer values so you use

例如,如果需要[5,10),则需要覆盖五个整数值,因此可以使用

Math.random() * 5

This would return a value in the range [0,5), where 5 is not included.

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

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

现在您需要将此范围向上移动到您的目标范围。您可以通过添加最小值来完成此操作。

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

You now will get a value in the range [Min,Max). Following our example, that means [5,10):

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

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

But, this still doesn't include Maxand you are getting a double value. In order to get the Maxvalue included, you need to add 1 to your range parameter (Max - Min)and then truncate the decimal part by casting to an int. This is accomplished via:

但是,这仍然不包括Max并且您获得了双重价值。为了获得Max包含的值,您需要将 1 添加到您的范围参数(Max - Min),然后通过转换为 int 截断小数部分。这是通过以下方式完成的:

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

And there you have it. A random integer value in the range [Min,Max], or per the example [5,10]:

你有它。范围内的随机整数值[Min,Max],或根据示例[5,10]

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

回答by Matt R

The Math.Randomclass in Javais 0-based. So, if you write something like this:

Java 中Math.Random类是基于 0 的。所以,如果你写这样的东西:

Random rand = new Random();
int x = rand.nextInt(10);

xwill be between 0-9inclusive.

x将介于两者之间0-9

So, given the following array of 25items, the code to generate a random number between 0(the base of the array) and array.lengthwould be:

因此,给定以下25项目数组,在0(数组的基数)和之间生成随机数的代码array.length将是:

String[] i = new String[25];
Random rand = new Random();
int index = 0;

index = rand.nextInt( i.length );

Since i.lengthwill return 25, the nextInt( i.length )will return a number between the range of 0-24. The other option is going with Math.Randomwhich works in the same way.

由于i.length将返回25nextInt( i.length )将返回范围之间的数字0-24。另一种选择是以Math.Random同样的方式工作的。

index = (int) Math.floor(Math.random() * i.length);

For a better understanding, check out forum post Random Intervals (archive.org).

为了更好地理解,请查看论坛帖子Random Intervals (archive.org)

回答by Matt R

Use:

用:

Random ran = new Random();
int x = ran.nextInt(6) + 5;

The integer xis now the random number that has a possible outcome of 5-10.

整数x现在是可能结果为 的随机数5-10

回答by sam

In case of rolling a dice it would be random number between 1 to 6 (not 0 to 6), so:

如果掷骰子,它将是 1 到 6(不是 0 到 6)之间的随机数,因此:

face = 1 + randomNumbers.nextInt(6);