如何在 Java 中生成特定区域的随机int?

如何在特定区域内生成一个随机的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`.

我帮你百度了一下,你可以参考下这个链接https://blog.csdn.net/Point9/article/details/84033421

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

在 Java 1.7或更高版本中,这样做:

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

这种方法的优点是不需要显式初始化java.util.Random。因为如果java.util.Random使用不当,可能会造成混乱和错误。
然而,反过来,也没有办法明确地设seed ,因此在测试或保存游戏状态或类似的情况下很难重现结果。在这些情况下,可以使用下面所示的 java1.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。 随机类通常比 java.lang 更可取

注意,这种方法比 nextInt 方法更加偏颇,效率也更低
实现这一点的一个标准模式是:
Min + (int)(Math.random() * ((Max - Min) + 1))
Java 数学库函数 Math.random ()在[0,1)区域内生成一个double value 。 注意这个范围不包括1。
为了首先得到一个特定的值范围,您需要乘以您想要覆盖的值范围的大小。
Math.random() * ( Max - Min )
这将return一个范围为[0,Max-Min ]的值,其中不包括“ Max-Min”。
例如,如果需要[5,10] ,则需要覆盖5个整数值,以便使用
Math.random() * 5
这将返回一个范围为[0,5]的值,其中不包括5。
现在你需要把这个区域转移到你的目标区域。您可以通过添加最小值来完成此操作。
Min + (Math.random() * (Max - Min))
现在将得到一个值范围 [Min,Max)。 按照我们的例子就是[5,10), :
5 + (Math.random() * (10 - 5))
但是,这仍然不包括Max和你得到的double value。 为了获得包含的 Max 值,需要向 range 参数添加 (Max - Min) ,然后通过转换为 int 来截断小数部分。这是通过以下途径实现的:
Min + (int)(Math.random() * ((Max - Min) + 1))
现在你知道了。 范围[ Min,Max ]中的随机整数值,或示例[5,10]中的随机整数值:
5 + (int)(Math.random() * ((10 - 5) + 1))

用这个:
Random ran = new Random();int x = ran.nextInt(6) + 5;
整数 x 现在是一个可能的结果为5-10的随机数。