繁体   English   中英

为2个数组赋值和对象 - Java

[英]Assigning Values to and Object from 2 arrays - Java

一直试图绕过这个逻辑,也许你们可以指出我正确的方向。

我有两个String [],一个包含Question Options,另一个包含选项是否正确。

例:

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

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

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

我将List传递给我的webservice,其中每个answerObject包含一个选项,以及它是否是正确的选项。

例:

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

answerObject.setAnswerText(Mangos);

answerObject.setAnswerCorrect(Y);

optionList.add(answerObject);

所以我的问题是,我将如何遍历数组并为每个对象分配正确的选项和optionCorrect。

谢谢任何愿意帮忙的人。

假设您的问题数组和答案数组是parllel

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

        answerObject.setAnswerCorrect(questionOptionsCorrect[i]);
    }

由于你有两个“并行”数组,你可以循环其中一个的索引,并使用两者的索引:

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]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM