有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

尝试1:

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

错误:randomNum可以大于maximum

尝试2:

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

错误:randomNum可以小于minimum


共 (6) 个答案

  1. # 1 楼答案

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

    Random rn = new Random();
    int range = maximum - minimum + 1;
    int randomNum =  rn.nextInt(range) + minimum;
    
  2. # 2 楼答案

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

    实现这一点的一个标准模式是:

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

    {a2}数学库函数Math。random()生成范围为[0,1)的双精度值。请注意,此范围不包括1

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

    Math.random() * ( Max - Min )
    

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

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

    Math.random() * 5
    

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

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

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

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

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

    但是,这仍然不包括Max,您将得到一个双精度值。为了获得包含的Max值,需要将1添加到范围参数(Max - Min),然后通过强制转换为int来截断小数部分。这通过以下方式实现:

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

    就在这里。范围为[Min,Max]的随机整数值,或根据示例[5,10]

    5 + (int)(Math.random() * ((10 - 5) + 1))
    
  3. # 3 楼答案

    使用:

    minimum + rn.nextInt(maxValue - minvalue + 1)
    
  4. # 4 楼答案

    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类通常比java.lang.Math.random()类更可取

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

  5. # 5 楼答案

    使用:

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

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

  6. # 6 楼答案

    中,他们在^{}类中引入了方法^{}

    例如,如果要生成[0,10]范围内的五个随机整数(或一个),只需执行以下操作:

    Random r = new Random();
    int[] fiveRandomNumbers = r.ints(5, 0, 11).toArray();
    int randomNumber = r.ints(1, 0, 11).findFirst().getAsInt();
    

    第一个参数仅指示生成的IntStream的大小(这是生成无限IntStream的方法的重载方法)

    如果需要执行多个单独的调用,可以从流中创建无限基本迭代器:

    public final class IntRandomNumberGenerator {
    
        private PrimitiveIterator.OfInt randomIterator;
    
        /**
         * Initialize a new random number generator that generates
         * random numbers in the range [min, max]
         * @param min - the min value (inclusive)
         * @param max - the max value (inclusive)
         */
        public IntRandomNumberGenerator(int min, int max) {
            randomIterator = new Random().ints(min, max + 1).iterator();
        }
    
        /**
         * Returns a random number in the range (min, max)
         * @return a random number in the range (min, max)
         */
        public int nextInt() {
            return randomIterator.nextInt();
        }
    }
    

    您还可以对doublelong值执行此操作。我希望有帮助!:)