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

当前回答

使用nexttint(n)方法为最小值和最大值的差值生成一个随机数,然后将最小值添加到结果中:

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

其他回答

Use:

minValue + rn.nextInt(maxValue - minValue + 1)

只需使用Random类:

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

你可以这样做:

import java.awt.*;
import java.io.*;
import java.util.*;
import java.math.*;

public class Test {

    public static void main(String[] args) {
        int first, second;

        Scanner myScanner = new Scanner(System.in);

        System.out.println("Enter first integer: ");
        int numOne;
        numOne = myScanner.nextInt();
        System.out.println("You have keyed in " + numOne);

        System.out.println("Enter second integer: ");
        int numTwo;
        numTwo = myScanner.nextInt();
        System.out.println("You have keyed in " + numTwo);

        Random generator = new Random();
        int num = (int)(Math.random()*numTwo);
        System.out.println("Random number: " + ((num>numOne)?num:numOne+num));
    }
}

让我们举个例子。

假设我希望生成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);

让我们了解这一点。。。

用最高值初始化max,用最低值初始化min。现在,我们需要确定可以获得多少可能的值。在本例中,应为:5, 6, 7, 8, 9, 10所以,这个计数应该是max-min+1。即10-5+1=6随机数将生成0-5之间的数字。即0、1、2、3、4、5将最小值添加到随机数将产生:5, 6, 7, 8, 9, 10 因此,我们获得了所需的范围。

最好使用SecureDrandom,而不仅仅是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;
}