File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Random numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Random numbers" Watch "Random numbers" New topic

Random numbers

Olliver Lim Kam Sian

Joined: Sep 26, 2007
Posts: 12
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.

marc weber

Joined: Aug 31, 2004
Posts: 11343

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
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
You could use java.util.Random.nextInt(max). Saves you from worrying about whether you got the rounding from double/float to int correct.

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
I agree. Here's the link:
subject: Random numbers
jQuery in Action, 3rd edition