Try this
public static void main(String args[]) throws Exception {
String[] answers = new String[4];
int len = answers.length;
answers[0] = "OS";
answers[1] = "GOOD";
answers[2] = "CS";
answers[3] = "Cody";
int random = getRandomNum(len);
System.out.println("random: " + random);
System.out.println(answers[random]);
}
private static int getRandomNum(int max) {
int rand = (int) (Math.random() * 100);
if (rand < max)
return rand;
return getRandomNum(max);
}
Output
Run 1
random: 3
Cody
Run 2
random: 1
GOOD
Update
if have to print all elements randomly in one run then this will helps
public static void main(String args[]) throws Exception {
String[] answers = new String[4];
int len = answers.length;
answers[0] = "OS";
answers[1] = "GOOD";
answers[2] = "CS";
answers[3] = "Cody";
for (int i = 0; i < len; i++) {
int random = getRandomNum(len);
System.out.println("random: " + random);
System.out.println(answers[random]);
}
}
private static int getRandomNum(int max) {
int rand = (int) (Math.random() * 100);
if (rand < max)
return rand;
return getRandomNum(max);
}
Output
random: 1
GOOD
random: 3
Cody
random: 0
OS
random: 2
CS
Update If you don't want any repeated values in your output, then head over to this simple and short method
public static void main(String args[]) throws Exception {
String[] answers = new String[4];
answers[0] = "OS";
answers[1] = "GOOD";
answers[2] = "CS";
answers[3] = "Cody";
List<String> list = Arrays.asList(answers);
System.out.println("Before: " + list.toString());
Collections.shuffle(list);
System.out.println("After: " + list.toString());
}
Output
Before: [OS, GOOD, CS, Cody]
After: [Cody, OS, GOOD, CS]
Hope this helps :)