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

2015/8/25

How to loop through existing objects?

SaxOps1 SaxOps1

2015/8/25

#
Ok, so I have a 14x14 2d array, which is looped through, and squares are added to the world (In all positions). Each square has a different colour (colourNum is an integer inside of the class), and is set inside of the Square.class. How can I loop through all of the objects and check if they are all of the same colour?
fejfo fejfo

2015/8/25

#
you can get all the squares like this :
1
getWorld().getObjects(Square.class);
and loop trough them like this
1
2
3
4
5
6
int color;
for(Squere s : getWorld().getObjects(Square.class)) {
    if(color == null) color = s.color;
    if(color != s.color) return false;
}
return true;
danpost danpost

2015/8/25

#
You cannot directly set the elements of the list returned by 'getObjects' to a variable of type Square without casting the elements to type Square first. You can replace line 2 with either this:
1
2
3
for (Object obj : getWorld().getObjects(Square.class))
{
    Square s = (Square)obj;
or with this (I believe this also works)
1
for (Square s : (java.util.List<Square>)getWorld().getObjects(Square.class)) {
SaxOps1 SaxOps1

2015/8/25

#
Thanks guys!
You need to login to post a reply.