我必须创建15个问题,其中只有10个将随机显示。(15个数组超过15个数组)。我需要确保在随机过程中没有重复的数组。
public static void main(String() args){
String question_1 = question_One();
//to question 15
String question_15 = question_fifteen();
String [] question = new String [14];
question[0] = question_1;
question[1] = question_2;
//to question 15
question[14] = question_15;
int random = (int) (Math.random()*11);
System.out.print(question[random]);
}
答案 0 :(得分:3)
我会采取一系列问题,将其改组,然后从形成前十个问题开始。但是,Java中的数组非常有限,使用适当的Collection
,例如ArrayList
:
// Build the question list:
List<String> questions = new ArrayList<>(15);
questions.add(question_1);
questions.add(question_2);
// etc...
// Shuffle it:
Collections.shuffle(questions);
// Ask the first ten:
List<String> questionsToAsk = questions.subList(0, 10);
编辑:
使用ArrayList
和Collections
只是一种便利。同样的逻辑也应该与数组一致,尽管它需要你自己实现一些:
// Build the question list:
String[] questions = new String[15];
questions[0] = question_1;
questions[1] = question_2;
// etc...
// Shuffle the first 10 elements.
// Although the elements can be taken from indexes above 10,
// there no need to continue shuffling these indexes.
Random r = new Random();
for (int i = 0; i < 10; ++i) {
int swapIndex = r.nextInt(15 - i) + i;
String temp = questions[i];
questions[i] = questions[swapIndex];
questions[swapIndex] = temp;
// Ask the first ten:
String[] questionsToAsk = new String[10];
for (int i = 0; i < 10; ++i) {
questionsToAsk[i] = questions[i];
}