Random numbers in Java when working with Android Random numbers in Java when working with Android android android

Random numbers in Java when working with Android


Docs are your friends

Random rand = new Random();int n = rand.nextInt(20); // Gives n such that 0 <= n < 20

Documentation:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. Thus, from this example, we'll have a number between 0 and 19


Math.random() returns an double from [0,1[.Random.nextInt(int) returns an int from [0, int[.


You can try:

int aNumber = (int) (20 * Math.random()) + 1;

or

Random rand = new Random();int n = rand.nextInt(20) + 1;