×

Discussion Board

Results 1 to 3 of 3
  1. #1
    Registered User
    Join Date
    Mar 2003
    Posts
    21

    problem with Random()

    Hi,

    I have some problems with Random(). My code is as follows.

    Random random = new Random();
    private int rand(int scale) {
    return (random.nextInt() << 1 >>> 1) % scale;
    }

    Whenever I write something like:

    int number = rand(9);

    It has null pointer exception.
    But if I use the above rand() function without assigning it to an integer, it works. eg:

    g.drawString("Number: " + rand(9), 0, 0, Graphics.LEFT | Graphics.TOP);

    Would you please tell me what is wrong?

    Thank you
    Nelson

  2. #2
    Nokia Developer Expert
    Join Date
    Mar 2003
    Posts
    382
    Hello

    Maybe you could use this;

    // example int limit = 100;

    int num = (int) (Math.abs(rnd.nextInt() % limit);

    This gives you only positive Integers from 0 - limit;

    I hope this helps you out

  3. #3
    Regular Contributor
    Join Date
    Mar 2003
    Location
    USA, FL
    Posts
    148
    May be you need this one? check it out:

    static Random m_rnd = new Random();

    public static int GetRnd(int min, int max)
    {
    int z = max - min;
    int r = m_rnd.nextInt() % z;
    return (min + Math.abs(r));
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •