Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

java - 如何在Java中生成特定范围内的随机整数?(How do I generate random integers within a specific range in Java?)

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

(如何生成特定范围内的随机int数值?)

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

(我已经尝试了以下方法,但是这些方法不起作用:)

Attempt 1:

(尝试1:)

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

Attempt 2:

(尝试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`.
  ask by user42155 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In Java 1.7 or later , the standard way to do this is as follows:

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

See the relevant JavaDoc .

(请参阅相关的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.

(这种方法的优点是不需要显式初始化java.util.Random实例,如果使用不当,可能会引起混乱和错误。)

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.

(在这种情况下,可以使用下面显示的Java 1.7之前的技术。)

Before Java 1.7 , the standard way to do this is as follows:

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

See the relevant JavaDoc .

(请参阅相关的JavaDoc 。)

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

(实际上, java.util.Random类通常比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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...