Saturday, April 13, 2013

Generate Random Numbers in Android

Bagikan :
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.


POSTING BERKAITAN




Template design by:
m-template | bagas96

0 comments:

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Post a Comment