Saturday, June 18, 2011

Generate Random Numbers in Android

In your apps (especially in game apps) , you may come across the need to generate random numbers. For generation of psuedo random numbers you can use random class from package java.util

First of all you can construct a random number generator using this

        mRandom = new Random(seed);

The seed should be unique for better results. You can use current time for that

                    Time t = new Time();
        t.setToNow();
        mRandom = new Random(t.toMillis(false));

Now to generate a random number from 0 to n, you can use mRandom.nextInt(n). Make sure that n is not zero.
          int rand = mRandom.nextInt(10);

The above line generates a random number between 0 to 9.

Random class also provides other functions such as nextFloat(), nextDouble, nextLong.

No comments:

Post a Comment