Java Math.random

Associate
Joined
10 Oct 2008
Posts
1,263
im using Math.random to generate random numbers but im looking to specify the range from it picks the numbers from eg. 66-100. does anyone know how to do this?
 
im using Math.random to generate random numbers but im looking to specify the range from it picks the numbers from eg. 66-100. does anyone know how to do this?

Code:
int number = 66 + new Random().nextInt(35);

The generator returns a number between 0 (inlcusive) and 35 (exlusive). Since the number is an integer it will range between 0 - 34 inclusive.

Now let us look at the bounds:

Assuming the number returned was 0, then 66 + 0 = 66.

Assuming the number returned was 34, then 66 + 34 = 100.

Everything else will sit in between.

PS: The Java API is your friend.
 
Last edited:
Back
Top Bottom