How to generate a random number from an array

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

int n [] = {1,7,3,5,8,10,33,12,18}
+3
source share
2 answers
import java.util.Random;

...

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

In the general case, get a random integer from the minimum value of 0 to the maximum length of the array -1 and use it as the index of the array.

0
source

Source: https://habr.com/ru/post/1738740/


All Articles