4

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

Community
  • 1
  • 1
user339108
  • 12,613
  • 33
  • 81
  • 112
  • 6
    People find it easier to google or ask here than THINK. – vulkanino Oct 11 '10 at 12:25
  • 2
    considering we have two deleted, one incorrect, and one severely edited answer, it could be more difficult than it first appears to be. – Thilo Oct 11 '10 at 12:27

3 Answers3

9

random.nextInt(max - min + 1) + min will do the trick. I assume you want min <= number <= max

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
9

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.

Margus
  • 19,694
  • 14
  • 55
  • 103
1

Example: Generating a number from 1 to 6
Because nextInt(6) returns a number from 0-5, it's necessary to add 1 to scale the number into the range 1-6

static Random randGen = new Random();
int spots;
. . .
spots = randGen.nextInt(6) + 1;
cloverink
  • 588
  • 8
  • 23