2013-10-04 35 views
1

一直試圖圍繞這個邏輯包圍我的頭,也許你們可以指引我朝着正確的方向。將值分配給2個數組和對象 - Java

我有兩個String [],一個包含Question選項,另一個選項是否正確。

例子:

String question = "Which of the following are fruit"; 

String[] questionOptions = "Mangos-Apples-Potatoes-Bananas".split("-"); 

String[] questionOptionsCorrect = "Y-Y-N-Y".split("-"); 

我傳遞一個List到我的web服務,其中每個answerObject包含一個選項,以及它是否是正確的選項。

例子:

List<AnswerObjects> optionList = new ArrayList<AnswerObjects>(); 

answerObject.setAnswerText(Mangos); 

answerObject.setAnswerCorrect(Y); 

optionList.add(answerObject); 

所以我的問題是,我怎麼會遍歷數組,並指定正確的選項,並optionCorrect到每個對象。

謝謝任何​​願意幫忙的人。

+1

也許從思考如何創建'AnswerObject'對象開始,以及如何將它們放入列表中。這可能會導致您進入下一步。 – Meesh

回答

1

既然你有兩個「平行」的陣列,您可以循環在其中一人的指標,並用兩個指標:

if (questionOptionsCorrect.length != questionOptions.length) { 
    // Throw an exception here: the arrays must have the same length 
    // for the code below to work 
} 
for (int i = 0 ; i != questionOptionsCorrect.length ; i++) { 
    AnswerObjects ans = new AnswerObjects(); 
    ans.setAnswerText(questionOptions[i]); 
    ans.setAnswerCorrect(questionOptionsCorrect[i]); 
} 
+0

完美地工作,謝謝你 – TheGoose

2

假設你的問題陣列和回答陣列parllel

for(int i = 0 ; i< questionOptions.length;i++) 
    { 
     AnswerObject answerObject = new AnswerObject(); 
     answerObject.setAnswerText(questionOptions[i]); 

     answerObject.setAnswerCorrect(questionOptionsCorrect[i]); 
    }