Velocity Reviews > Java > Generate a random number

Generate a random number

RayKnight
Guest
Posts: n/a

 04-29-2005
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
Guest
Posts: n/a

 04-29-2005
RayKnight wrote:
> 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.
>

http://java.sun.com/j2se/1.5.0/docs/...il/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)

--
Peter MacMillan
e-mail/msn: http://www.velocityreviews.com/forums/(E-Mail Removed)

Peter MacMillan
Guest
Posts: n/a

 04-29-2005
Peter MacMillan wrote:
> RayKnight wrote:
>
>
> 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;

--
Peter MacMillan
e-mail/msn: (E-Mail Removed)