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

当前回答

这将生成范围(最小值-最大值)不重复的随机数列表。

generateRandomListNoDuplicate(1000, 8000, 500);

添加此方法。

private void generateRandomListNoDuplicate(int min, int max, int totalNoRequired) {
    Random rng = new Random();
    Set<Integer> generatedList = new LinkedHashSet<>();
    while (generatedList.size() < totalNoRequired) {
        Integer radnomInt = rng.nextInt(max - min + 1) + min;
        generatedList.add(radnomInt);
    }
}

希望这对你有所帮助。

其他回答

int func(int max, int min){

      int range = max - min + 1;
      
      // Math.random() function will return a random no between [0.0,1.0).
      int res = (int) ( Math.random()*range)+min;

      return res;
}
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);

}

下面是一个简单的示例,它显示了如何从闭合的[min,max]范围生成随机数,而min<=max为真

您可以将其作为孔中字段类重用,也可以将所有Random.class方法放在一个位置

结果示例:

RandomUtils random = new RandomUtils();
random.nextInt(0, 0); // returns 0
random.nextInt(10, 10); // returns 10
random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)
random.nextInt(10, -10); // throws assert

来源:

import junit.framework.Assert;
import java.util.Random;

public class RandomUtils extends Random {

    /**
     * @param min generated value. Can't be > then max
     * @param max generated value
     * @return values in closed range [min, max].
     */
    public int nextInt(int min, int max) {
        Assert.assertFalse("min can't be > then max; values:[" + min + ", " + max + "]", min > max);
        if (min == max) {
            return max;
        }

        return nextInt(max - min + 1) + min;
    }
}

使用Apache Lang3 Commons

Integer.parseInt(RandomStringUtils.randomNumeric(6, 6));

最小值100000到最大值999999

您可以使用以下方法来执行此操作:

int range = 10;
int min = 5
Random r = new Random();
int = r.nextInt(range) + min;