Justin - 9 months ago 52

Android Question

I need to make a random number between 1 and 20, and based on that number (using "If - Then" statements), I need to set the image of an ImageView.

I know that in Objective-C, it goes like this:

`int aNumber = arc4Random() % 20;`

if (aNumber == 1) {

[theImageView setImage:theImage];

}

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

`int aNumber = (int) Math.random()`

Answer Source

```
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