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

当前回答

Random rng = new Random();
int min = 3;
int max = 11;
int upperBound = max - min + 1; // upper bound is exclusive, so +1
int num = min + rng.nextInt(upperBound);
System.out.println(num);

其他回答

范围[最小值最大值](含)内的随机数:

int randomFromMinToMaxInclusive = ThreadLocalRandom.current()
        .nextInt(min, max + 1);

在A和b之间生成n个随机数的简单方法例如a=90,b=100,n=20

Random r = new Random();
for(int i =0; i<20; i++){
    System.out.println(r.ints(90, 100).iterator().nextInt());
}

r.ints()返回一个IntStream,并有几个有用的方法,看看它的API。

使用Java 8 Streams,

传递初始容量-多少个数字将randomBound从x传递到randomBoud是否为已排序传递true/false传递新的Random()对象

 

public static List<Integer> generateNumbers(int initialCapacity, int randomBound, Boolean sorted, Random random) {

    List<Integer> numbers = random.ints(initialCapacity, 1, randomBound).boxed().collect(Collectors.toList());

    if (sorted)
        numbers.sort(null);

    return numbers;
}

在本例中,它从1-Randombound生成数字。

一般使用java.utilforRandom。

您可以定义最小和最大范围以获得这些结果。

Random rand=new Random();
rand.nextInt((max+1) - min) + min;

如果你不想重新发明轮子,这里有一个简单明了的解决方案:

RandomStringUtils.randomNumeric(count); // Where count is the number of digits you want in the random number.

Apache Commons,例如组件Lang中的RandomUtils,提供了许多选项来生成任意格式的随机数。