简体   繁体   中英

For loop inside other for loop

I have a String array like this:

one
twoo
three
four
five
six
seven
eight
nine

For each 3 elements, I want to create a new object setting fields of that object to the elements. For example:

one
twoo
three 

would be used like:

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

I think that I have to use one for inside other but I don´t know how.

I have tried like this but bad result:

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

The simplest approach is to use one loop but iterate by 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: The English word for the number 2 is spelled "two".

You should try to only use one loop iterated by 3 if you're sure that myarray will always have a size equals to x*3.

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

Then on the beginning of each iteration, you have to recreate a new mipartido object ( but declare it before the loop)

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

By using this, your ArrayList should be filled with 3 mipartido objects, all diferents. But remember that your "myarray" size must be a multiple of 3.

I really like Bohemain's answer , but I wanted to suggest an alternative using the Modulus operator (that I think OP was going for in the original post).

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

You could do it this way such that your for loop still increments by one each time, but you alternate the method call. As explained here , the operator simply gets the remainder.

So as you increment, the switch statement will work like this:

0 % 3 = 0 , 1 % 3 = 1 , 2 % 3 = 2 , 3 % 3 = 0 , etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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