Generate a random number

Discussion in 'Java' started by RayKnight, Apr 29, 2005.

  1. RayKnight

    RayKnight Guest

    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.
     
    RayKnight, Apr 29, 2005
    #1
    1. Advertising

  2. 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/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)


    --
    Peter MacMillan
    e-mail/msn:
     
    Peter MacMillan, Apr 29, 2005
    #2
    1. Advertising

  3. 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:
     
    Peter MacMillan, Apr 29, 2005
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Matt
    Replies:
    24
    Views:
    9,368
    Malcolm
    Oct 18, 2004
  2. Acacia

    Generate a random number

    Acacia, Aug 25, 2003, in forum: C++
    Replies:
    6
    Views:
    550
    Kevin Goodsell
    Aug 26, 2003
  3. Wahoo
    Replies:
    4
    Views:
    465
    Jerry Coffin
    May 18, 2004
  4. globalrev
    Replies:
    4
    Views:
    774
    Gabriel Genellina
    Apr 20, 2008
  5. VK
    Replies:
    15
    Views:
    1,179
    Dr J R Stockton
    May 2, 2010
Loading...

Share This Page