EN
Java - pick random string from array of strings
8 points
We need to generate random index of an array.
As nextInt
function is called we pass int bound
to have results within array size.
xxxxxxxxxx
1
import java.util.concurrent.ThreadLocalRandom;
2
3
public class JavaRandomStringFromArray {
4
5
public static String randomStringFromArr() {
6
String[] arr = {"A", "B", "C", "D", "E", "F"};
7
int randIdx = ThreadLocalRandom.current().nextInt(arr.length);
8
String randomElem = arr[randIdx];
9
return randomElem;
10
}
11
12
public static void main(String[] args) {
13
System.out.println(randomStringFromArr()); // F
14
System.out.println(randomStringFromArr()); // B
15
System.out.println(randomStringFromArr()); // A
16
}
17
}