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

/** Generate random integers in a certain range. */
public final class RandomRange {

  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");

    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }

    log("Done.");
  }

  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if ( aStart > aEnd ) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);    
    log("Generated : " + randomNumber);
  }

  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 

此类的示例运行:

Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.

其他回答

Java中的Math.Random类是基于0的。所以,如果你这样写:

Random rand = new Random();
int x = rand.nextInt(10);

x将介于0-9之间(含0-9)。

因此,给定以下25项的数组,生成0(数组的基数)和array.length之间的随机数的代码为:

String[] i = new String[25];
Random rand = new Random();
int index = 0;

index = rand.nextInt( i.length );

由于i.length将返回25,因此nextInt(i.length)将返回0-24之间的数字。另一个选项是Math.Random,其工作方式相同。

index = (int) Math.floor(Math.random() * i.length);

为了更好地理解,请查看论坛帖子Random Intervals(archive.org)。

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();

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

你可以使用

RandomStringUtils.randomNumeric(int count)

该方法也来自Apache Commons。

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);

我想知道Apache Commons Math库提供的任何随机数生成方法是否符合要求。

例如:RandomDataGenerator.nextInt或RandomDataGenerator.nextLong