Jessy
Jessy

Reputation: 15661

how to generate random number from array

How to generate random number from an array? and not from a range.

int n [] = {1,7,3,5,8,10,33,12,18}

Upvotes: 3

Views: 23806

Answers (2)

kbenson
kbenson

Reputation: 1464

In general terms, get a random integer ranging from a minimum of 0 to a maximum of the array length -1, and use that as the array index.

Upvotes: 0

Barthelemy
Barthelemy

Reputation: 8777

import java.util.Random;

...

Random random = new Random();
System.out.println(n[random.nextInt(n.length)]);

Upvotes: 16

Related Questions