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

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

我尝试了以下方法,但是这些方法无效:

尝试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,random,integer

Q: How do I generate random integers within a specific range in Java?

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

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

Attempt 1:

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

Attempt 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`.

回答1:

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

请参见相关的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;
}

请参见相关的JavaDoc 。实际上, java .util.Random 类通常优于 java.lang.Math.random()

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

A1:

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

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.

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.

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

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

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.

回答2:

请注意,这种方法比nextInt方法 https:// stackoverflow .com / a / 738651/360211

一种实现此目的的标准模式是:

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

Java 数学库函数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值,您需要在范围参数(Max-Min)中加1,然后通过强制转换为int截断小数部分。这是通过以下方式完成的:

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

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

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

A2:

Note that this approach is more biased and less efficient than a nextInt approach, https://stackoverflow.com/a/738651/360211

One standard pattern for accomplishing this is:

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

The Java Math library function Math.random() generates a double value in the range [0,1). Notice this range does not include the 1.

In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.

Math.random() * ( Max - Min )

This returns a value in the range [0,Max-Min), where 'Max-Min' is not included.

For example, if you want [5,10), you need to cover five integer values so you use

Math.random() * 5

This would return a value in the range [0,5), where 5 is not included.

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

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

You now will get a value in the range [Min,Max). Following our example, that means [5,10):

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

But, this still doesn't include Max and you are getting a double value. In order to get the Max value included, you need to add 1 to your range parameter (Max - Min) and then truncate the decimal part by casting to an int. This is accomplished via:

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

And there you have it. A random integer value in the range [Min,Max], or per the example [5,10]:

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

回答3:

使用:

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

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

A3:

Use:

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

The integer x is now the random number that has a possible outcome of 5-10.

回答4:

使用:

minimum + rn.nextInt(maxValue - minvalue + 1)

A4:

Use:

minimum + rn.nextInt(maxValue - minvalue + 1)

回答5:

带有他们介绍了方法 ints(int randomNumberOrigin,int randomNumberBound) rel="noreferrer"> Random 类。

例如,如果要生成范围为[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值进行此操作。

希望有帮助! :)

A5:

With they introduced the method ints(int randomNumberOrigin, int randomNumberBound) in the Random class.

For example if you want to generate five random integers (or a single one) in the range [0, 10], just do:

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

The first parameter indicates just the size of the IntStream generated (which is the overloaded method of the one that produces an unlimited IntStream).

If you need to do multiple separate calls, you can create an infinite primitive iterator from the stream:

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

You can also do it for double and long values.

Hope it helps! :)

回答6:

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

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

A6:

You can edit your second code example to:

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

回答7:

只需对您的第一个解决方案进行少量修改即可。

Random rand = new Random();
randomNum = minimum + rand.nextInt((maximum - minimum) + 1);

在此处查看更多有关 随机

A7:

Just a small modification of your first solution would suffice.

Random rand = new Random();
randomNum = minimum + rand.nextInt((maximum - minimum) + 1);

See more here for implementation of Random

回答8:

Java 中的Math.Random类基于0。因此,如果您编写这样的内容:

Random rand = new Random();
int x = rand.nextInt(10);

x将介于0-9之间。

因此,给定以下由25个项目组成的数组,该代码将生成一个介于0(数组的基数)和array.length之间的随机数.为:

String[] i = new String[25];
Random rand = new Random();
int index = 0;

index = rand.nextInt( i.length );

由于i.length将返回25,因此nextInt(i.length)将返回一个介于范围之间的数字0-24 。另一个选择是使用Math.Random,它的工作方式相同。

index = (int) Math.floor(Math.random() * i.length);

为了更好地理解,请查看论坛帖子 随机间隔(archive.org)

A8:

The Math.Random class in Java is 0-based. So, if you write something like this:

Random rand = new Random();
int x = rand.nextInt(10);

x will be between 0-9 inclusive.

So, given the following array of 25 items, the code to generate a random number between 0 (the base of the array) and array.length would be:

String[] i = new String[25];
Random rand = new Random();
int index = 0;

index = rand.nextInt( i.length );

Since i.length will return 25, the nextInt( i.length ) will return a number between the range of 0-24. The other option is going with Math.Random which works in the same way.

index = (int) Math.floor(Math.random() * i.length);

For a better understanding, check out forum post Random Intervals (archive.org).

回答9:

ThreadLocalRandom与类java.util.Random等效,用于多线程环境。生成随机数是在每个线程中本地执行的。因此,通过减少冲突,我们可以获得更好的性能。

int rand = ThreadLocalRandom.current().nextInt(x,y);

x,y-间隔例如(1,10)

A9:

ThreadLocalRandom equivalent of class java.util.Random for multithreaded environment. Generating a random number is carried out locally in each of the threads. So we have a better performance by reducing the conflicts.

int rand = ThreadLocalRandom.current().nextInt(x,y);

x,y - intervals e.g. (1,10)

回答10:

请原谅我讲究,但是大多数人建议的解决方案,即min+rng.nextInt(max-min+1))似乎很危险,原因是:

  • rng.nextInt(n)无法达到Integer.MAX_VALUE
  • min为负数时,
  • (max-min)可能导致溢出。

万无一失的解决方案将为[Integer.MIN_VALUEInteger.MAX_VALUE]中的任何min<=max返回正确的结果。考虑以下简单的实现:

int nextIntInRange(int min, int max, Random rng) {
   if (min > max) {
      throw new IllegalArgumentException("Cannot draw random int from invalid range [" + min + ", " + max + "].");
   }
   int diff = max - min;
   if (diff >= 0 && diff != Integer.MAX_VALUE) {
      return (min + rng.nextInt(diff + 1));
   }
   int i;
   do {
      i = rng.nextInt();
   } while (i < min || i > max);
   return i;
}

尽管效率很低,但请注意,while循环中成功的概率将始终为50%或更高。

A10:

Forgive me for being fastidious, but the solution suggested by the majority, i.e., min + rng.nextInt(max - min + 1)), seems perilous due to the fact that:

  • rng.nextInt(n) cannot reach Integer.MAX_VALUE.
  • (max - min) may cause overflow when min is negative.

A foolproof solution would return correct results for any min <= max within [Integer.MIN_VALUE, Integer.MAX_VALUE]. Consider the following naive implementation:

int nextIntInRange(int min, int max, Random rng) {
   if (min > max) {
      throw new IllegalArgumentException("Cannot draw random int from invalid range [" + min + ", " + max + "].");
   }
   int diff = max - min;
   if (diff >= 0 && diff != Integer.MAX_VALUE) {
      return (min + rng.nextInt(diff + 1));
   }
   int i;
   do {
      i = rng.nextInt();
   } while (i < min || i > max);
   return i;
}

Although inefficient, note that the probability of success in the while loop will always be 50% or higher.

回答11:

只需执行以下语句即可完成

Randomizer.generate(0,10); //min of zero, max of ten

以下是其源代码

Randomizer.java

public class Randomizer {
    public static int generate(int min,int max) {
        return min + (int)(Math.random() * ((max - min) + 1));
    }
}

这很干净简单。

A11:

It can be done by simply doing the statement:

Randomizer.generate(0,10); //min of zero, max of ten

Below is its source-code

Randomizer.java

public class Randomizer {
    public static int generate(int min,int max) {
        return min + (int)(Math.random() * ((max - min) + 1));
    }
}

It is just clean and simple.

A12:

I wonder if any of the random number generating methods provided by an Apache Commons Math library would fit the bill.

For example: RandomDataGenerator.nextInt or RandomDataGenerator.nextLong

回答13:

让我们举个例子。

假设我希望生成一个介于 5-10 之间的数字:

int max = 10;
int min = 5;
int diff = max - min;
Random rn = new Random();
int i = rn.nextInt(diff + 1);
i += min;
System.out.print("The Random Number is " + i);

让我们理解这一点 ...

用最大值初始化最大值,用最小值初始化最小值。

现在,我们需要确定可以获得多少个可能的值。对于此示例,它将是:

5、6、7、8、9、10

因此,此计数为max-min +1。

即10-5 + 1 = 6

随机数将生成一个介于 0-5 之间的数字。

即0、1、2、3、4、5

min 值添加到随机数将产生:

5、6、7、8、9、10

因此,我们获得了所需的范围。

A13:

Let us take an example.

Suppose I wish to generate a number between 5-10:

int max = 10;
int min = 5;
int diff = max - min;
Random rn = new Random();
int i = rn.nextInt(diff + 1);
i += min;
System.out.print("The Random Number is " + i);

Let us understand this...

Initialize max with highest value and min with the lowest value.

Now, we need to determine how many possible values can be obtained. For this example, it would be:

5, 6, 7, 8, 9, 10

So, count of this would be max - min + 1.

i.e. 10 - 5 + 1 = 6

The random number will generate a number between 0-5.

i.e. 0, 1, 2, 3, 4, 5

Adding the min value to the random number would produce:

5, 6, 7, 8, 9, 10

Hence we obtain the desired range.

回答14:

 rand.nextInt((max+1) - min) + min;

A14:

 rand.nextInt((max+1) - min) + min;

回答15:

通过使用 nextint(n)方法,然后将最小值添加到结果中:

Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);

A15:

Generate a random number for the difference of min and max by using the nextint(n) method and then add min number to the result:

Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);

回答16:

从Java 7开始,您不应再使用Random。对于大多数用途,现在选择的随机数生成器为 ThreadLocalRandom

对于fork连接池和并行流,请使用 SplittableRandom

约书亚·布洛赫(Joshua Bloch)。有效的Java。第三版。

从Java 8开始

对于fork连接池和并行流,请使用SplittableRandom,该速度通常更快,与Random相比,具有更好的统计独立性和统一性。

要生成范围为[0,1_000]:

的随机int
int n = new SplittableRandom().nextInt(0, 1_001);

要生成随机的int[100]值数组,范围为[0,1_000]:

int[] a = new SplittableRandom().ints(100, 0, 1_001).parallel().toArray();

要返回随机值流:

IntStream stream = new SplittableRandom().ints(100, 0, 1_001);

A16:

As of Java 7, you should no longer use Random. For most uses, the random number generator of choice is now ThreadLocalRandom.

For fork join pools and parallel streams, use SplittableRandom.

Joshua Bloch. Effective Java. Third Edition.

Starting from Java 8

For fork join pools and parallel streams, use SplittableRandom that is usually faster, has a better statistical independence and uniformity properties in comparison with Random.

To generate a random int in the range [0, 1_000]:

int n = new SplittableRandom().nextInt(0, 1_001);

To generate a random int[100] array of values in the range [0, 1_000]:

int[] a = new SplittableRandom().ints(100, 0, 1_001).parallel().toArray();

To return a Stream of random values:

IntStream stream = new SplittableRandom().ints(100, 0, 1_001);

回答17:

使用这种方法可能很方便:

此方法将在提供的最小值和最大值之间返回一个随机数

public static int getRandomNumberBetween(int min, int max) {
    Random foo = new Random();
    int randomNumber = foo.nextInt(max - min) + min;
    if (randomNumber == min) {
        // Since the random number is between the min and max values, simply add 1
        return min + 1;
    } else {
        return randomNumber;
    }
}

,此方法将从提供的最小值和最大值返回一个随机数 (因此生成的数字也可以是最小值或最大值):

public static int getRandomNumberFrom(int min, int max) {
    Random foo = new Random();
    int randomNumber = foo.nextInt((max + 1) - min) + min;

    return randomNumber;
}

A17:

This methods might be convenient to use:

This method will return a random number between the provided min and max value:

public static int getRandomNumberBetween(int min, int max) {
    Random foo = new Random();
    int randomNumber = foo.nextInt(max - min) + min;
    if (randomNumber == min) {
        // Since the random number is between the min and max values, simply add 1
        return min + 1;
    } else {
        return randomNumber;
    }
}

and this method will return a random number from the provided min and max value (so the generated number could also be the min or max number):

public static int getRandomNumberFrom(int min, int max) {
    Random foo = new Random();
    int randomNumber = foo.nextInt((max + 1) - min) + min;

    return randomNumber;
}

回答18:

我用这个:

 /**
   * @param min - The minimum.
   * @param max - The maximum.
   * @return A random double between these numbers (inclusive the minimum and maximum).
   */
 public static double getRandom(double min, double max) {
   return (Math.random() * (max + 1 - min)) + min;
 }

如果需要,可以将其转换为整数。

A18:

I use this:

 /**
   * @param min - The minimum.
   * @param max - The maximum.
   * @return A random double between these numbers (inclusive the minimum and maximum).
   */
 public static double getRandom(double min, double max) {
   return (Math.random() * (max + 1 - min)) + min;
 }

You can cast it to an Integer if you want.

回答19:

这是一个有用的类,可以在具有包含/不包含边界的任意组合的范围内生成随机的ints

import java.util.Random;

public class RandomRange extends Random {
    public int nextIncInc(int min, int max) {
        return nextInt(max - min + 1) + min;
    }

    public int nextExcInc(int min, int max) {
        return nextInt(max - min) + 1 + min;
    }

    public int nextExcExc(int min, int max) {
        return nextInt(max - min - 1) + 1 + min;
    }

    public int nextIncExc(int min, int max) {
        return nextInt(max - min) + min;
    }
}

A19:

Here's a helpful class to generate random ints in a range with any combination of inclusive/exclusive bounds:

import java.util.Random;

public class RandomRange extends Random {
    public int nextIncInc(int min, int max) {
        return nextInt(max - min + 1) + min;
    }

    public int nextExcInc(int min, int max) {
        return nextInt(max - min) + 1 + min;
    }

    public int nextExcExc(int min, int max) {
        return nextInt(max - min - 1) + 1 + min;
    }

    public int nextIncExc(int min, int max) {
        return nextInt(max - min) + min;
    }
}

回答20:

如果掷骰子,它将是1到6之间的随机数(而不是0到6),所以:

face = 1 + randomNumbers.nextInt(6);

A20:

In case of rolling a dice it would be random number between 1 to 6 (not 0 to 6), so:

face = 1 + randomNumbers.nextInt(6);

回答21:

要生成"两个数字之间"的随机数,请使用以下代码:

Random r = new Random();
int lowerBound = 1;
int upperBound = 11;
int result = r.nextInt(upperBound-lowerBound) + lowerBound;

这将为您提供一个介于1(含)和11(不含)之间的随机数,因此请通过加1来初始化upperBound值。例如,如果要生成介于1到10之间的随机数,请使用11而不是10。

A21:

To generate a random number "in between two numbers", use the following code:

Random r = new Random();
int lowerBound = 1;
int upperBound = 11;
int result = r.nextInt(upperBound-lowerBound) + lowerBound;

This gives you a random number in between 1 (inclusive) and 11 (exclusive), so initialize the upperBound value by adding 1. For example, if you want to generate random number between 1 to 10 then initialize the upperBound number with 11 instead of 10.

回答22:

int random = minimum + Double.valueOf(Math.random()*(maximum-minimum )).intValue();

或者从 Apache Commons 中查看RandomUtils。

A22:

int random = minimum + Double.valueOf(Math.random()*(maximum-minimum )).intValue();

Or take a look to RandomUtils from Apache Commons.

回答23:

只需使用 Random 类:

Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);

A23:

Just use the Random class:

Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);

回答24:

您可以在Java 8中简洁地实现这一目标:

Random random = new Random();

int max = 10;
int min = 5;
int totalNumber = 10;

IntStream stream = random.ints(totalNumber, min, max);
stream.forEach(System.out::println);

A24:

You can achieve that concisely in Java 8:

Random random = new Random();

int max = 10;
int min = 5;
int totalNumber = 10;

IntStream stream = random.ints(totalNumber, min, max);
stream.forEach(System.out::println);

回答25:

我发现了这个示例生成随机数


此示例生成特定范围内的随机整数。

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {

  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");

    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }

    log("Done.");
  }

  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if ( aStart > aEnd ) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);    
    log("Generated : " + randomNumber);
  }

  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 

此类的示例运行:

Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.

A25:

I found this example Generate random numbers :


This example generates random integers in a specific range.

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {

  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");

    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }

    log("Done.");
  }

  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if ( aStart > aEnd ) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);    
    log("Generated : " + randomNumber);
  }

  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 

An example run of this class :

Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.

回答26:

public static Random RANDOM = new Random(System.nanoTime());

public static final float random(final float pMin, final float pMax) {
    return pMin + RANDOM.nextFloat() * (pMax - pMin);
}

A26:

public static Random RANDOM = new Random(System.nanoTime());

public static final float random(final float pMin, final float pMax) {
    return pMin + RANDOM.nextFloat() * (pMax - pMin);
}

回答27:

当您需要大量随机数时,建议不要在API中使用Random类。周期太短了。请尝试使用梅森捻线器。有 Java实现

A27:

When you need a lot of random numbers, I do not recommend the Random class in the API. It has just a too small period. Try the Mersenne twister instead. There is a Java implementation.

回答28:

另一个选择是仅使用 Apache Commons

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

public void method() {
    RandomData randomData = new RandomDataImpl();
    int number = randomData.nextInt(5, 10);
    // ...
 }

A28:

Another option is just using Apache Commons:

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

public void method() {
    RandomData randomData = new RandomDataImpl();
    int number = randomData.nextInt(5, 10);
    // ...
 }

回答29:

最好使用 SecureRandom 不仅仅是随机的。

public static int generateRandomInteger(int min, int max) {
    SecureRandom rand = new SecureRandom();
    rand.setSeed(new Date().getTime());
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}

A29:

It's better to use SecureRandom rather than just Random.

public static int generateRandomInteger(int min, int max) {
    SecureRandom rand = new SecureRandom();
    rand.setSeed(new Date().getTime());
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}

回答30:

这里是一个简单的示例,显示了如何从封闭的[min,max]范围生成随机数,而min<=max是true

您可以将其作为孔类中的字段重用,也可以将所有Random.class方法放在一个地方

结果示例:

RandomUtils random = new RandomUtils();
random.nextInt(0, 0); // returns 0
random.nextInt(10, 10); // returns 10
random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)
random.nextInt(10, -10); // throws assert

来源:

import junit.framework.Assert;
import java.util.Random;

public class RandomUtils extends Random {

    /**
     * @param min generated value. Can't be > then max
     * @param max generated value
     * @return values in closed range [min, max].
     */
    public int nextInt(int min, int max) {
        Assert.assertFalse("min can't be > then max; values:[" + min + ", " + max + "]", min > max);
        if (min == max) {
            return max;
        }

        return nextInt(max - min + 1) + min;
    }
}

A30:

Here is a simple sample that shows how to generate random number from closed [min, max] range, while min <= max is true

You can reuse it as field in hole class, also having all Random.class methods in one place

Results example:

RandomUtils random = new RandomUtils();
random.nextInt(0, 0); // returns 0
random.nextInt(10, 10); // returns 10
random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)
random.nextInt(10, -10); // throws assert

Sources:

import junit.framework.Assert;
import java.util.Random;

public class RandomUtils extends Random {

    /**
     * @param min generated value. Can't be > then max
     * @param max generated value
     * @return values in closed range [min, max].
     */
    public int nextInt(int min, int max) {
        Assert.assertFalse("min can't be > then max; values:[" + min + ", " + max + "]", min > max);
        if (min == max) {
            return max;
        }

        return nextInt(max - min + 1) + min;
    }
}
回到顶部