如何在Java中生成特定范围内的随机整数? [英] How to generate random integers within a specific range in Java?

查看:151
本文介绍了如何在Java中生成特定范围内的随机整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I generate a random int value in a specific range?

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

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

尝试1:

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

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


推荐答案

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

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

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 实例,如果使用不当,可能会造成混淆和错误。

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

然而,反过来说没有办法明确地设置种子,因此很难在有用的情况下重现结果,例如测试或保存游戏状态或类似情况。在这些情况下,可以使用下面显示的Java之前的1.7技术。

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:

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

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

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

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.

这篇关于如何在Java中生成特定范围内的随机整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆