我根据您的需要编写了一个完整的程序。但是,请看看我在做什么。只需一点上下文,这就是我创建的:
// initialize a random object once.
Random random = new Random();
// the question
String question = "With what letter does the name start of the new president of the USA?";
// here are some basic answers
String[] answers = new String[] {
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k"
};
// you already know the correct index of the array above, in this case it's d
int index = 3;
// this array will contain four answers, including correct one!
String[] four = new String[4];
// get answer index, we will place correct value in that index
int answerIndex = random.nextInt(four.length);
// now lets pick 4 answers!
for (int i = 0; i < four.length; i++) {
// we are at the answer index!
if (i == answerIndex) {
four[i] = answers[index];
continue;
}
int randomIndex = random.nextInt(answers.length);
for (int j = 0; j < four.length; j++) {
// we got duplicate here!
if (answers[randomIndex].equals(four[j])) {
randomIndex = random.nextInt(answers.length);
// redo this current iteration
j = j - 1;
}
}
four[i] = answers[randomIndex];
}
输出:
e, c, d, h
g, d, d, h
d, g, e, f
d, f, b, i
g, d, a, b
c, d, g, b
h, d, e, k
e, f, d, c
k, d, e, h
i, d, e, d
如果你解释你在哪里使用它,以及你已经编码的内容的简短演示,这将有所帮助。