如何在特定范围内生成随机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`.

当前回答

import java.util.Random;

public class RandomSSNTest {

    public static void main(String args[]) {
        generateDummySSNNumber();
    }


    //831-33-6049
    public static void generateDummySSNNumber() {
        Random random = new Random();

        int id1 = random.nextInt(1000);//3
        int id2 = random.nextInt(100);//2
        int id3 = random.nextInt(10000);//4

        System.out.print((id1+"-"+id2+"-"+id3));
    }

}

您也可以使用

import java.util.concurrent.ThreadLocalRandom;
Random random = ThreadLocalRandom.current();

然而,这个类在多线程环境中表现不佳。

其他回答

以前的大多数建议都不考虑“溢出”。例如:min=整数.min_VALUE,max=100。到目前为止,我采用的正确方法之一是:

final long mod = max- min + 1L;
final int next = (int) (Math.abs(rand.nextLong() % mod) + min);

我已经创建了一个方法来获取给定范围内的唯一整数。

/*
      * minNum is the minimum possible random number
      * maxNum is the maximum possible random number
      * numbersNeeded is the quantity of random number required
      * the give method provides you with unique random number between min & max range
*/
public static Set<Integer> getUniqueRandomNumbers( int minNum , int maxNum ,int numbersNeeded ){

    if(minNum >= maxNum)
        throw new IllegalArgumentException("maxNum must be greater than minNum");

    if(! (numbersNeeded > (maxNum - minNum + 1) ))
        throw new IllegalArgumentException("numberNeeded must be greater then difference b/w (max- min +1)");

    Random rng = new Random(); // Ideally just create one instance globally

    // Note: use LinkedHashSet to maintain insertion order
    Set<Integer> generated = new LinkedHashSet<Integer>();
    while (generated.size() < numbersNeeded)
    {
        Integer next = rng.nextInt((maxNum - minNum) + 1) + minNum;

        // As we're adding to a set, this will automatically do a containment check
        generated.add(next);
    }
    return generated;
}

从Java7开始,您应该不再使用Random。对于大多数用途选择的随机数生成器现在ThreadLocalRandom。用于fork连接池和并行流,使用SplitableRandom。

乔舒亚·布洛赫。有效的Java。第三版。

从Java 8开始

对于fork-join池和并行流,请使用SplittableRandom,它通常更快,与Random相比具有更好的统计独立性和一致性财产。

要生成[0,1_000]范围内的随机整数:

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

要生成[0,1_000]范围内的随机整数[100]数组,请执行以下操作:

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

要返回随机值流:

IntStream stream = new SplittableRandom().ints(100, 0, 1_001);
public static void main(String[] args) {

    Random ran = new Random();

    int min, max;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter min range:");
    min = sc.nextInt();
    System.out.println("Enter max range:");
    max = sc.nextInt();
    int num = ran.nextInt(min);
    int num1 = ran.nextInt(max);
    System.out.println("Random Number between given range is " + num1);

}

有一个图书馆在https://sourceforge.net/projects/stochunit/用于处理范围的选择。

StochIntegerSelector randomIntegerSelector = new StochIntegerSelector();
randomIntegerSelector.setMin(-1);
randomIntegerSelector.setMax(1);
Integer selectInteger = randomIntegerSelector.selectInteger();

它具有边缘包含/排除。