Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random numbers in Java when working with Android

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()
like image 552
Justin Avatar asked Jul 19 '11 00:07

Justin


People also ask

What is random () in android?

Generates random bytes and places them into a user-supplied byte array. Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

How do you generate a random number from 1 to 10 in Java?

For example, to generate a random number between 1 and 10, we can do it like below. ThreadLocalRandom random = ThreadLocalRandom. current(); int rand = random. nextInt(1, 11);


1 Answers

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

like image 186
trutheality Avatar answered Oct 20 '22 21:10

trutheality