Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random value between two numbers [duplicate]

Tags:

java

Possible Duplicate:
Java: generating random number in a range

How do I generate a random value between two numbers. Random.nextInt() gives you between 0 and the passed value. How do I generate a value between minValue and a maxValue

like image 353
user339108 Avatar asked Dec 03 '22 04:12

user339108


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

This also takes account for facts, that nextInt() argument must be positive, and that from can be bigger then to.

like image 125
Margus Avatar answered May 21 '23 08:05

Margus