• Status: Solved
• Priority: Medium
• Security: Public
• Views: 4552

# using Math.random to generate an integer from 1 to 10

from Right

How can I generate a random integer from 1 to 10 using the Math.random() method.
0
Right
• 3
• 2
1 Solution

Commented:

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.
0

Commented:
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("n must be positive");

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.
0

Commented:
this looks a cool method!
0

Commented:
0

Commented:
LOL!

Objects, pitty this isn't rated a hard question! :o(

ahem!

Anyhow, I don't deserve the points (and a 'B' rating for such an amazing answer as mine? bah!), so I'f you want to get the points you deserve from the mods, I wont take offence. (I think Right was just asleep...)

:o)
0

Commented:
Lab Rat,

Thanks for the concern :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.