Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Random numbers

 
Olliver Lim Kam Sian
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use java.util.Random.nextInt(max). Saves you from worrying about whether you got the rounding from double/float to int correct.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic