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

当前回答

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

}

其他回答

尝试使用org.apachemons.lang.RandomStringUtils类。是的,它有时会给出一个相邻的重复数字,但它会给出介于5和15之间的值:

    while (true)
    {
        int abc = Integer.valueOf(RandomStringUtils.randomNumeric(1));
        int cd = Integer.valueOf(RandomStringUtils.randomNumeric(2));
        if ((cd-abc) >= 5 && (cd-abc) <= 15)
        {
            System.out.println(cd-abc);
            break;
        }
    }

只需对第一个解决方案稍作修改即可。

Random rand = new Random();
randomNum = minimum + rand.nextInt((maximum - minimum) + 1);

有关Random的实现,请参阅此处的更多信息

Use:

Random ran = new Random();
int x = ran.nextInt(6) + 5;

整数x现在是可能结果为5-10的随机数。

您可以使用Random类生成随机数,然后使用.nextInt(maxNumber)生成随机数。maxNumber是生成随机数时所需的最大值。请记住,Random类给你的是0到maxNumber-1的数字。

Random r = new Random();
int i = r.nextInt();

另一种方法是使用Math.Random()类,许多学校的课程都要求您使用该类,因为它更高效,而且您不必声明新的Random对象。要使用Math.random()获取随机数,请键入:

Math.random() * (max - min) + min;
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;
    }
}