Random numbers in Java when working with Android

I need to make a random number from 1 to 20 and based on this number (using the "If-Then" instructions), I need to install an ImageView image.

I know that in Objective-C it looks something like this:

int aNumber = arc4Random() % 20; if (aNumber == 1) { [theImageView setImage:theImage]; } 

How can I do this in Java? I saw how this is done, but I do not see how I can set the range of numbers (1-20, 2-7, ect).

 int aNumber = (int) Math.random() 
+12
source share
5 answers

Documents are your friends

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

Documentation

Returns a pseudo-random uniformly distributed int value between 0 (inclusive) and the given value (exceptional) taken from this sequence of random number generators. So from this example we will have a number from 0 to 19

+37
source

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

+5
source

You can try:

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

or

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

You can use Math.random () to generate a double between 0 and 1, not inclusive. Android Javadoc is here .

0
source
 Random r = new Random(); int number = r.nextInt(20); 
-one
source

All Articles