In Java, writing a function to get a random number from a range is not that hard.
It is just a matter of finding the correct function to cleanly convert from Double
to Integer
.
A lot of time is wasted to find how to do that as I'm not familiar with the
functions they offer. I simply want to put this out here so that later, if needed, I can get it from here.
Get a random integer from a range
Math.random()
returns a random decimal number between 0 and 1. You can treat it as percentage.
Multiple that random decimal number to the range between a
and b
. Then, convert it to an integer.
And, finally, add it to a
.
Here is the code:
public static int getRandomInt(int a, int b){ int range = b-a; double rndDouble = Math.random()*range; return Double.valueOf(rndDouble).intValue()+a; }