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

当前回答

另一种选择是使用Apache Commons:

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

public void method() {
    RandomData randomData = new RandomDataImpl();
    int number = randomData.nextInt(5, 10);
    // ...
 }

其他回答

import java.util.Random; 

public class RandomUtil {
    // Declare as class variable so that it is not re-seeded every call
    private static Random random = new Random();

    /**
     * Returns a psuedo-random number between min and max (both inclusive)
     * @param min Minimim value
     * @param max Maximim value. Must be greater than min.
     * @return Integer between min and max (both inclusive)
     * @see java.util.Random#nextInt(int)
     */
    public static int nextInt(int min, int max) {
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        return random.nextInt((max - min) + 1) + min;
    }
}

这是实现这一点的简单方法。

import java.util.Random;
class Example{
    public static void main(String args[]){
        /*-To test-
        for(int i = 1 ;i<20 ; i++){
            System.out.print(randomnumber()+",");
        }
        */

        int randomnumber = randomnumber();

    }

    public static int randomnumber(){
        Random rand = new Random();
        int randomNum = rand.nextInt(6) + 5;

        return randomNum;
    }
}

其中5是随机数的起点。6是包括数字5的范围。

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

您可以按以下方式操作。

import java.util.Random;
public class RandomTestClass {

    public static void main(String[] args) {
        Random r = new Random();
        int max, min;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter maximum value : ");
        max = scanner.nextInt();
        System.out.println("Enter minimum value : ");
        min = scanner.nextInt();
        int randomNum;
        randomNum = r.nextInt(max) + min;
        System.out.println("Random Number : " + randomNum);
    }

}

使用Apache Lang3 Commons

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

最小值100000到最大值999999