2014-11-05 83 views
0

我有一个ArrayList>我从PHP 这里存储我的提问者它看起来像{{question,optA,optB,optC,optD,answer},{question,optA,optB,optC,optD,answer} ,.....}}Android ArrayList Shuffle

我该如何洗牌只有我的A,B,C,D像D,B,A,C? {问题,optD,optB,OPTA,OPTC,回答}使用

林这段代码

//myArray 
     ArrayList<ArrayList<String>> getQuestion = new ArrayList<ArrayList<String>>(); 
     ArrayList<String> choices; 


     //first retrive elements from getQuestionArray 
     questIndex = getQuestion.get(arrayRow).get(0); 
     aIndex = getQuestion.get(arrayRow).get(1); 
     bIndex = getQuestion.get(arrayRow).get(2); 
     cIndex = getQuestion.get(arrayRow).get(3); 
     dIndex = getQuestion.get(arrayRow).get(4); 
     answerIndex = getQuestion.get(arrayRow).get(5); 


     //get the correct answer (This is Word of senteces) 
     String correctAnswer = ""; 
     if(answerIndex.equals("a")){ 
      correctAnswer = aIndex; 
     }else if(answerIndex.equals("b")){ 
      correctAnswer = bIndex; 
     }else if(answerIndex.equals("c")){ 
      correctAnswer = cIndex; 
     }else if(answerIndex.equals("d")){ 
      correctAnswer = dIndex; 
     } 

     //Im using this to shuffle my abcd Im creating new ArrayList for that 
     choices.add(aIndex); 
     choices.add(bIndex); 
     choices.add(cIndex); 
     choices.add(dIndex); 

     Collections.shuffle(choices); 

     int correctIndex; 
     //Find now where is our correct answer 
     correctIndex = choices.indexOf(correctAnswer); 


     //our correct letter now 
     switch(correctIndex){ 
     case 0: 
      answerIndex = "a"; 
      break; 
     case 1: 
      answerIndex = "b"; 
      break; 
     case 2: 
      answerIndex = "c"; 
      break; 
     case 3: 
      answerIndex = "d"; 
      break; 
     } 

     aIndex = choices.get(0); 
     bIndex = choices.get(1); 
     cIndex = choices.get(2); 
     dIndex = choices.get(3); 

     question.setText(questIndex); 
     cA.setText(aIndex); 
     cB.setText(bIndex); 
     cC.setText(cIndex); 
     cD.setText(dIndex); 

有没有办法做到这一点?

+0

你Should't初始化你选择的ArrayList? – joao2fast4u 2014-11-05 15:22:09

+0

你的实现有什么问题? – joao2fast4u 2014-11-05 15:38:08

回答

0

我将创建一个类MyQuestion这个字段:

public class MyQuestion{ 
    String question; 
    String answer; 
    List<String> options; 
} 

,然后调用Collections.shuffle(选件);

或者你创建这样的方法:

public static void shuffle(List list, int a, int b){ 
     List shuffleList = new ArrayList(); 
     for (int i = a; i <= b; i++) 
      shuffleList.add(list.get(i)); 
     Collections.shuffle(shuffleList); 
     for (int i = a; i i<= b; i++) 
      list.set(i, shuffleList.get(i-a)); 
    } 

我没有使用泛型只是要快,但它很容易将它们添加