# Random numbers

Olliver Lim Kam Sian

Greenhorn

Posts: 12

posted 9 years ago

Hello everyone,i'm having problem to generate random numbers within a certain range.I am using the following code:

computersNumber = (int)(100 * Math.random()) + 1;

The prob with this code is that it returns an integer between 1 and 100.

I would like one that generate within a range for example 50 and 60.

Hope to get some help.

Thank you for considering my problem.

cheers

Olliver

computersNumber = (int)(100 * Math.random()) + 1;

The prob with this code is that it returns an integer between 1 and 100.

I would like one that generate within a range for example 50 and 60.

Hope to get some help.

Thank you for considering my problem.

cheers

Olliver

posted 9 years ago

Welcome to JavaRanch!

As you know, Math.random() returns a double between 0.0 and 1.0 (including the lower boundary 0.0, but not the upper 1.0). So multiplying this by an int x gives you a double between 0.0 and x. Now, if you want to shift this range up or down, just add or subtract.

You're already doing this by adding 1 in your example, to shift the range from 0-99 up by 1 to 1-100. So if you want numbers between 50 and 60 (let's say including 50 but not 60), you could use (Math.random() * 10) to get a double between 0.0 and 10.0, then add 50 to shift this to 50.0 and 60.0. That is...

(int)(Math.random() * 10) + 50)

Originally posted by Olliver Lim Kam Sian:

...I would like one that generate within a range for example 50 and 60...

Welcome to JavaRanch!

As you know, Math.random() returns a double between 0.0 and 1.0 (including the lower boundary 0.0, but not the upper 1.0). So multiplying this by an int x gives you a double between 0.0 and x. Now, if you want to shift this range up or down, just add or subtract.

You're already doing this by adding 1 in your example, to shift the range from 0-99 up by 1 to 1-100. So if you want numbers between 50 and 60 (let's say including 50 but not 60), you could use (Math.random() * 10) to get a double between 0.0 and 10.0, then add 50 to shift this to 50.0 and 60.0. That is...

(int)(Math.random() * 10) + 50)

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." *~Joe Strummer*

sscce.org