对于其他for循环内部的循环

时间:2015-01-07 22:33:41

标签: java for-loop

我有一个像这样的String数组:

one
twoo
three
four
five
six
seven
eight
nine

对于每3个元素,我想创建一个新对象,将该对象的字段设置为元素。例如:

one
twoo
three 

将被用作:

obj.setOne("one");
obj.setTwoo("twoo");
obj.setThree("three");

我认为我必须在其他地方使用一个,但我不知道如何。

我试过这样但效果不好:

ArrayList<MyClass> myobjects;
MyClass my_object = new MyClass();

for (int z = 0; z < myarray.size(); z++) {
    for (z = 0; z < (z + 3) && z < myarray.size(); i++) {
        if (i == 0) {
            mipartido.setAttributeOne(datos.get(i));
        }
        else if (i == 1) {
            mipartido.setAttributteTwoo(datos.get(i));
        }
        else if (i == 2) {
            mipartido.setAttributeThree(datos.get(i));
        }
        myobjects.add(mipartido);
    }
}

3 个答案:

答案 0 :(得分:1)

最简单的方法是使用一个循环但迭代3:

for (int i = 0; i < myarray.size() - 2; i+=3) {
    mipartido.setAttributeOne(myarray.get(i));
    mipartido.setAttributeTwoo(myarray.get(i+1));
    mipartido.setAttributeThree(myarray.get(i+2));
}

FYI:数字2的英文单词拼写为&#34; 2&#34;。

答案 1 :(得分:0)

如果你确定myarray的大小总是等于x * 3,你应该尝试只使用一个迭代3的循环。

            MyClass mipartido;
            for  (z=0; z< myarray.size(); z+=3){

然后在每次迭代开始时,你必须重新创建一个新的mipartido对象(但在循环之前声明它)

                mipartido = new MyClass();
                mipartido.setAttributeOne(datos.get(i));
                mipartido.setAttributteTwoo(datos.get(i+1));
                mipartido.setAttributeThree(datos.get(i+2));
                myobjects.add(mipartido);
        }

通过使用它,你的ArrayList应该填充3个mipartido对象,所有不同的东西。 但要记住你的&#34; myarray&#34;大小必须是3的倍数。

答案 2 :(得分:0)

我真的很喜欢Bohemain's answer,但我想建议使用Modulus operator的替代方案(我认为OP在原帖中会有用)。

for (int i = 0; i < myarray.size(); i++) {
    switch (i % 3) {
        case 0:
            mipartido.setAttributeOne(myarray.get(i));
        case 1:
            mipartido.setAttributeTwo(myarray.get(i));
        case 2:
            mipartido.setAttributeThree(myarray.get(i));
    }
}

你可以这样做,这样你的for循环每次仍然增加一个,但你交替方法调用。正如here所述,操作员只需获取余数。

因此,当您递增时,switch语句将如下所示:

0 % 3 = 01 % 3 = 12 % 3 = 23 % 3 = 0

相关问题