How do I generate random integers within a specifi

2020-01-22 10:52发布

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

30条回答
Lonely孤独者°
2楼-- · 2020-01-22 11:25

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.

查看更多
等我变得足够好
3楼-- · 2020-01-22 11:25

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2020-01-22 11:25

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);
查看更多
劫难
5楼-- · 2020-01-22 11:26

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.

查看更多
狗以群分
6楼-- · 2020-01-22 11:27

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;
}
查看更多
Luminary・发光体
7楼-- · 2020-01-22 11:30

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);
查看更多
登录 后发表回答