如何在Java的特定范围内生成随机整数?| Java Debug 笔记

1,179 阅读2分钟

本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看活动链接

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

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

我试过以下几个,但这些都不起作用:

尝试 1:

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

错误:可以大于.randomNummaximum

尝试2:

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

错误:可以小于。randomNumminimum

高分回答:

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

有关爪哇多克请参阅。此方法的优点是不需要明确初始化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;
}

有关爪哇多克请参阅。在实践中,java.util.Random通常优于java.lang.Math.random().。

特别是,当标准库内有直接的 API 来完成任务时,无需重新发明随机整数生成轮。

高分回答:

如下是doc文档里的,是本文作者截取部分供读者扩展:

ThreadLocalRandom

实例是线程安全(CAS)。但是,在线程中同时使用同一实例可能会遇到争议,并由此造成性能不佳。考虑在多读设计中使用线程本地随机。java.util.Randomjava.util.Random

实例在加密上不安全。考虑使用SecureRandom获取加密安全伪随机数生成器,供安全敏感应用程序使用。java.util.Random

文章翻译自 stackoverflow.com/questions/3…

作者建议: 建议使用1.8的案例,关于它还有一个问答,看下一篇

真心感谢帅逼靓女们能看到这里,如果这个文章写得还不错,觉得有点东西的话

求点赞👍 求关注❤️ 求分享👥 对8块腹肌的我来说真的 非常有用!!!

如果本篇博客有任何错误,请批评指教,不胜感激 !❤️❤️❤️❤️