user2005938
user2005938

Reputation: 179

For statement not working for every array element?

This question is about Android/AndEngine but pertains to Java in general.

I have a for loop for attaching handling rectangles that are in an array. This is my code.

try {
        if ((NPCrectangle.size() > 0) && (NPCbody.size() > 0)) {
            System.out.println("NPCrectangle size is "+NPCrectangle.size());
            for (int i = 0; i < NPCrectangle.size(); i++) {
                System.out.println("For loop ran for NPCrectangle "+i);
                for (int j = 0; j < NPCbody.size(); j++) {
                    NPCrectangle.get(i).setX(NPCbody.get(j).getPosition().x*32);
                    attachChild(NPCrectangle.get(i));
                    System.out.println("RECTANGLE ATTACHED FOR NPC"+i);
                }
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
    }

At

System.out.println("NPCrectangle size is "+NPCrectangle.size());
        for (int i = 0; i < NPCrectangle.size(); i++) {
            System.out.println("For loop ran for NPCrectangle "+i);

I get 'NPCrectangle size is 2', but then I only get 'For loop ran for NPCrectangle 0'. It never does anything with the second element of the array. Why is this?

This is my catch:

04-25 18:45:45.420: W/System.err(2235): java.lang.IllegalStateException: pEntity 'Rectangle' already has a parent: 'GameScene'. New parent: 'GameScene'!
04-25 18:45:45.420: W/System.err(2235):     at org.andengine.entity.Entity.assertEntityHasNoParent(Entity.java:1707)
04-25 18:45:45.420: W/System.err(2235):     at org.andengine.entity.Entity.attachChild(Entity.java:907)

Which is an error when you try to attach the same sprite twice. Suggestions?

Upvotes: 0

Views: 136

Answers (1)

HalR
HalR

Reputation: 11073

This loop

for (int j = 0; j < NPCbody.size(); j++) {
                    NPCrectangle.get(i).setX(NPCbody.get(j).getPosition().x*32);
                    attachChild(NPCrectangle.get(i));
                    System.out.println("RECTANGLE ATTACHED FOR NPC"+i);

is run multiple times, depending on NPCbody.size(), but will attach the same rectangle. NPCrectangle.get(i), each time. Hence you get the error the second time through the inner loop.

Upvotes: 2

Related Questions