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

标签 java random integer

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

最佳答案

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

参见the relevant 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;
}

参见the relevant JavaDoc 。在实践中,java.util.Random class 通常优于 java.lang.Math.random() .

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

关于java - 如何在Java中生成特定范围内的随机整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61611306/

相关文章:

java - Java WebDriver程序中如何获取浏览器的响应流

java - solr boost函数的目的

java - 在 SpringMVC 中,我在 Centos 7 STS 中部署和运行另一个系统的项目,它给出了错误

python - 整数在SQlite中记录良好,但在MySQL中记录为0

java - 什么是堆栈溢出错误?

visual-c++ - 在MFC,VC++,多线程应用程序上挂起/随机崩溃

python - 快速选择范围内一定百分比的元素

java - Bukkit/Java 可定制的百分比机会

Java Integer 添加前导零?

c++ - 是什么决定一个整数类型默认是有符号的还是无符号的?