问题描述
我有两个问题和答案数组
I've got two arrays of question and answers
String questions[] = {
"Q1?",
"Q2?",
"Q3?"};
String answers[] = {
"A1?",
"A2?",
"A3?"};
我用 Collections.shuffle(Arrays.asList(questions);
对每个数组进行洗牌。如何对每个数组进行洗牌,以便在洗牌后它们保持相同的顺序?
I used Collections.shuffle(Arrays.asList(questions);
to shuffle each arrays. How do I shuffle each array so that after shuffling they maintain same order?
推荐答案
你可以改为一个包含索引的新数组。然后从第一个索引中获取两个数组中的元素。
You can rather shuffle a new array which holds the indices. And then get the elements from both array from the first index.
List<Integer> indexArray = Arrays.asList(0, 1, 2);
Collections.shuffle(indexArray);
String question = questions[indexArray.get(0)];
String answer = answers[indexArray.get(0)];
当然,创建一个类
包含问题
和答案
将是一种更为OO的方式,正如其他答案所暗示的那样。那样,你只需维护一个 List
或 array
,与当前方法中的 3数组
相比。
Of course, creating a class
containing questions
and answers
would be a more OO way, as other answers suggest. That way, you would have to maintain just one List
or array
, as compared to 3 arrays
in the current approach.
这篇关于如何在java中以相同的顺序混洗两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!