-1

I need a very simple random number generator function that takes a input parameter as a range something like:

int randomNumberGenerater(int range) {
    return (int) (Math.random() * range);
}

The trouble is when the range is equal to 1, it will always output 1 instead of alternating between 0 and 1. How can I fix that with a generic solution that works with any range if possible.

Michał Powaga
  • 22,561
  • 8
  • 51
  • 62
user1935724
  • 554
  • 1
  • 6
  • 18
  • The post suggested has hundreds of answers and did not even have a author accepted answer, does that mean we need to read through those suggestions to find the one we need????? Incredibly stupid thing and not sure who wants to come here if you need to spend another half an hour to figure out your answer – user1935724 Sep 29 '13 at 19:07

5 Answers5

3

Use Random class, and it's nextInt(int) method to generate the random number from 0 to a given integer number:

public static int randomNumberGenerater(int range) {
    Random rand = new Random();
    return rand.nextInt(range);
}
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2
Random random = new Random();
int randomNumberGenerater(int range) {
    return random.nextInt(range);
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

Using the Random class allows you to specify a range.

Random rand = new Random();
rand.nextInt(range);
Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

You can go for ceil() or floor() functions to get equal number of 0's and 1's.

In case, if your random generation method gives out 0.3 or 0.8, your method will always give you 1. But if you use these two methods mentioned, you will get evenly distributed 0's and 1's.

Manikandan Sigamani
  • 1,964
  • 1
  • 15
  • 28
0

You could always just use apache-commons-lang's RandomUtils: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/RandomUtils.html#nextInt(int)

Mureinik
  • 297,002
  • 52
  • 306
  • 350