Ran into a similar problem with pulling a random string from a string array.
Found this to work fairly well, I applied it to a button action so with every click a random is drawn(I found with any array size there are multiple instances of the same string being drawn consecutively throughout):
import java.util.*;
import java.util.Random.*;
class Countries {
public Random g2 = new Random();
public String[] list = new String[] { "Finland", "Russia",
"Latvia", "Lithuania", "Poland" };
String random2;
}
// Applied to a button action:
int INDEXn = g2.nextInt(list.length);
for (int i2 = 0; i2 < INDEXn; i2++) {
random2 = (String) (list[INDEXn]);
}
System.out.println(random2 + '\n');
The g2
random that is being used by INDEXn
is calling a random integer, in this case the defined strings are turned into integer values, from the String array list
.
The for-loop is cycling through the String array one time.
The random2 string is converting the chosen integer from INDEXn
to the appropriate string variable in (list[INDEXn]
).