How to create a random value between two numbers

Possible duplicate:
Java: generating a random number in a range

How to create a random value between two numbers. Random.nextInt () gives from 0 to the passed value. How to create a value between minValue and maxValue

+3
source share
3 answers

Write a method like:

public static int getRandom(int from, int to) {
    if (from < to)
        return from + new Random().nextInt(Math.abs(to - from));
    return from - new Random().nextInt(Math.abs(to - from));
}

It also takes into account the facts that the argument nextInt()must be positive, and from there can be more to .

+7
source

random.nextInt(max - min + 1) + minwill do the trick. I guess you wantmin <= number <= max

+9
source

Example: creating a number from 1 to 6
Since nextInt (6) returns a number from 0 to 5, you need to add 1 to scale the number in the range 1-6

static Random randGen = new Random ();
int spots;
. . .
spots = randGen.nextInt (6) + 1;
+1
source

Source: https://habr.com/ru/post/1768972/


All Articles