AP-Computer-Science ScienceAP
Random Numbers Random Numbers
Math.random()
Returns a pseudorandom double in , using a shared random-number generator internally.
Generate an integer in
For integer bounds a < b and a positive b - a that fits in int:
int myRandInt = a + (int) (Math.random() * (b - a));
Correction to the original example
The original cast surrounded the addition of
a:(int) (Math.random() * (b - a) + a). Casting truncates toward zero, so that version gives the wrong interval for negative lower bounds. Cast the nonnegative offset first, then adda.
Source: Math.random.
Related: Type casting · Arithmetic