This site requires JavaScript, please enable it in your browser!
Greenfoot back
bishal52
bishal52 wrote ...

2017/9/28

For each loop

bishal52 bishal52

2017/9/28

#
Hi, can anyone please share me an example of for each loop. I'm having a problem with it. Thank you
danpost danpost

2017/9/28

#
A for each loop just iterates through a list of objects to perform actions on some or all of them. It may also be that no specific type was found and so no actions were actually performed. As an example, the list might be all Ball objects that intersect an actor and each must animate by changing colors continuously while intersecting the actor. It would be a behavior of a Ball object to change colors, so a method in the Ball class should be constructed to perform that duty, let us call it 'agitateColor()'. The actor could then have a method called 'agitateBalls()' which would look like this:
1
2
3
4
private void agitateBalls()
{
    for (Ball ball : (List<Ball>)getIntersectingObjects(Ball.class)) ball.agitateColor();
}
In simpler form, it might look like this:
1
2
3
4
private void agitateBalls()
{
    for (Object obj : getIntersectingObjects(Ball.class)) ((Ball)obj).agitateColor();
}
Or, broken down even more, like this:
1
2
3
4
5
6
7
8
private void agitateBalls()
{
    for (Object obj : getIntersectingObjects(Ball.class))
    {
        Ball ball = (Ball)obj;
        ball.agitateColor();
    }
}
Now, let us say that there are Box objects also and when intersecting the actor, they would oscillate in size. Then, it could be done like this:
1
2
3
4
5
6
7
8
private void agitateIntersectors()
{
    for (Object obj : getIntersectingObjects(Actor.class))
    {
        if (obj instanceof Ball) ((Ball)obj).agitateColor();
        if (obj instanceof Box) ((Box)obj).agitateSize();
    }
}
davmac davmac

2017/9/28

#
Note that with the current version of Greenfoot, the first version can be written without a cast:
1
2
3
4
private void agitateBalls()
{
    for (Ball ball : getIntersectingObjects(Ball.class)) ball.agitateColor();
}
You need to login to post a reply.