Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / April 2005

Tip: Looking for answers? Try searching our database.

Generate a random number

Thread view: 
RayKnight - 29 Apr 2005 06:38 GMT
If I want to generate a random number between a certain number, what might
possibly be the formulae?

Example if I were to make a game, and the minimum damage is 10 and the
maximum is 35. So what might possibly be the formulae to generate a random
number between 10 to 35?

Any help or link is appreciated. Thank you.
Peter MacMillan - 29 Apr 2005 06:48 GMT
> If I want to generate a random number between a certain number, what might
> possibly be the formulae?
[quoted text clipped - 4 lines]
>
> Any help or link is appreciated. Thank you.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html

int num = (new Random()).nextInt(35 - 10) + 10;

(note that it's probably better to store the Random object in a variable
somewhere for reuse... possible an instance variable, but that's a
design choice I leave to you)

Signature

Peter MacMillan
e-mail/msn: peter@writeopen.com

Peter MacMillan - 29 Apr 2005 06:57 GMT
> int num = (new Random()).nextInt(35 - 10) + 10;

just a note that nextInt excludes the upper-bound. So if you wanted to
include 35 as a possible result, you'd have to add 1 to it.

ie.
/* ... */.nextInt(max + 1 - min) + min;

Signature

Peter MacMillan
e-mail/msn: peter@writeopen.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.