You better off using the nextInt() method in the Random class. And if you're using a JDK prior to 1.2 then here's the code:
public int nextInt(int n)
{
if (n<=0)
throw new IllegalArgumentException("
if ((n & -n) == n) // i.e., n is a power of 2
return (int)((n * (long)next(31)) >> 31);
int bits, val;
do {
bits = next(31);
val = bits % n;
} while(bits - val + (n-1) < 0);
return val;
}
Using Math.random() doesn't allow you any control over the random number seeding and will also be slower due to unnecessary floating point arithmetic.
Main Topics
Browse All Topics





by: jpkPosted on 2001-09-16 at 17:54:17ID: 6486365
int intNum = (int) 10 * java.lang.Math.random();
Since Random returns a a double between 0.0 and 1.0, multipling by 10 will return a value between 0.0 and 1.0. Then cast it to an int.