Java - for循环:分发

时间:2015-01-30 16:23:23

标签: java for-loop

我如何分配超过8位父母的510名儿童,以便我在前7位中的每一位都有64位,其余62位于8位,每位父母的ID为9至72位。

到目前为止,我有这个:

// first 7 parents will have 64 children each, 8th parent will have 62 children
for(int child = 1; child <= maxNumChildren; child++) {
    setTestStep("Create Child = " + child + " on Parent = " + ((child/65) + 1)  + " with childId = " + ( 9 + ((child- 1) % 64)));
    childList[child - 1] = createChild(parentList[child/65], child, "" + ( 9 + ((child- 1) % 64)));
}

这是错误的,因为第129个孩子是在第3个父母的第2个孩子上创建的,依此类推。

你能帮我解决这个问题吗?

P.S。对不起,如果我使用了一些错误的术语,我是初学者。

2 个答案:

答案 0 :(得分:0)

这应该会产生正确的结果。

final int step = 64;
for (int i = 0; i < maxNumChildren; i += step) {
    for (int j = i; j < Math.min(maxNumChildren, i+step); j++) {
        childList[j] = createChild(parentList[i/step], j+1, "" + (9+j-i));
    }
}

答案 1 :(得分:0)

您可以使用从零开始的索引来修复您所拥有的索引算术。

// first 7 parents will have 64 children each,
// 8th parent will have 62 children
for(int childIndex = 0; childIndex < maxNumChildren; childIndex++) {
    setTestStep("Create Child = " + (childIndex + 1) +
                " on Parent = " + ((childIndex / 64) + 1)  +
                " with childId = " + ( 9 + childIndex % 64));
    childList[childIndex] = createChild(parentList[childIndex / 64],
                                        child, "" + ( 9 + (childIndex % 64));
}