Java-for循环:分发

Java-for循环:分发,java,for-loop,Java,For Loop,我怎样才能将510个孩子分配给8位家长,这样前7位家长中就有64位,第8位家长中有62位,每个家长的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

我怎样才能将510个孩子分配给8位家长,这样前7位家长中就有64位,第8位家长中有62位,每个家长的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)));
}
//前7位家长每人将有64个孩子,第8位家长将有62个孩子

对于(int child=1;child这将产生正确的结果

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));
    }
}
final int step=64;
对于(int i=0;i
通过使用基于零的索引,您可以修复现有的索引算法

// 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));
}
//前7位家长每人将有64个孩子,
//第八位家长将有62个孩子
对于(int childIndex=0;childIndex
2个循环会让事情变得更加清晰,而不是使用
child-1
child=0
开始,使用
/64
而不是
/65
clildList
子列表
?编辑:clildList是childList。谢谢:)@user2576486-我不确定我是否理解您的高级程序员的反对意见。除非这会导致大量的开销,否则您最好还是提高可读性,而不是一些微小的性能改进。