Generate a random number

R

RayKnight

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.
 
P

Peter MacMillan

RayKnight said:
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/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)
 
P

Peter MacMillan

Peter said:
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;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top