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

2012/3/2

How to get coordinates of List objects

MattT MattT

2012/3/2

#
List ships = getObjects(Boat.class);
int[] shipsOnSea = new int [10];
// The tens are the length of the List ships
for (int i = 0; i < 10; i++)
{
        shipsOnSea[i] = (ships.get(i)).getX();
}
So basically in my world class, I want to scan all the Boat objects, then get the X coordinate for each one of them to determine who is closest to the left of the screen. How can I make it work? Would it be easier if I made an array for each boat on the screen (and how can I do it if it is recommend)?
danpost danpost

2012/3/2

#
List ships = getObjects(Boat.class);
int leftX = 999; // to track lowest X coordinate
Boat leftBoat = null; // to hold the leftmost boat found so far
for (Boat ship : ships) // format of 'for' to iterate through a list
{
    if (ship.getX() < leftX)
    {
        leftBoat = ship;
        leftX = ship.getX();
    }
}
The above code should end up with 'leftBoat' being a reference to the leftmost Boat object in your world and 'leftX' would equal 'leftBoat.getX()'.
MattT MattT

2012/3/2

#
So I tried to the code you sent me, reformatted the for statement:
List ships = getObjects(Boat.class);
int leftX = 999; // to track lowest X coordinate
Boat leftBoat = null; // to hold the leftmost boat found so far
for (int i = 0; i < ships.size(); i++) // format of 'for' to iterate through a list
{
    if ((ships.get(i)).getX() < leftX)
    {
          leftBoat = ships;
          leftX = ships.get(i).getX();

     }
}
Unfortunately, I do not know how to run methods inside List objects. Any suggestions? Thank you. :)
Duta Duta

2012/3/2

#
MattT wrote...
Unfortunately, I do not know how to run methods inside List objects. Any suggestions? Thank you. :)
Do you mean methods held inside Boat.class? If so, here's a code snippet demonstrating it:
List<Boat> ships = getObjects(Boat.class);
(ships.get(x)).aMethod();
Where x is the boat's position within the list
You need to login to post a reply.