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

2013/3/17

Arrays and coordinates

Shawn Shawn

2013/3/17

#
Alright guys bear with me for a moment, I'm trying to create an array than when I call it out using System.out.println( "("+LocationX+ "," +LocationY+")" ); it prints for me all the current objects (which in this case is the rocks) location in X and Y format. Here's my code:
public class Rock extends Objects
{
    int LocationX[] = {0};
    int LocationY[] = {0};

    public void act() 
    {
        rockPosition();
        rocksRecord();

    }  
        
    public void rockPosition()
    {
     
       int x = getX();
       int y = getY();
       
       int LocationX[];
       int LocationY[];
       
       
    }
    
    public void rocksRecord()
    {
        System.out.println( "("+Lx[i]+ "," +Ly[i]+")" );   
    }
}
I know the code is wrong but what can I do to make it work?
Gevater_Tod4711 Gevater_Tod4711

2013/3/17

#
Well I don't know if this is even possible if you want to use arrays. Arrays have a length that you can't change and therefore there aren't enought fields in the array for the rocks. The easyest way to get the location off all rock objects would be to get the references to every rock object using getObjects(Rock.class) and then print their location That should work like this:
for (Actor actor : getWorld().getObjects(Rock.class)) {//also you can use any other class or null if you want to get the position of every object in the world;
    System.out.println(actor.getX() + " " + actor.getY());
}
Or if you want to get more information about the object you can declare the method toString in the class you want the objects to be printet on the screen. If you then print your objects using System.out.println(actor); (see the example before) the method println will automaticly call the method toString of this object. Then you just have to declare a method toString like this one:
public String toString() {
    return getX() + " " + getY() + "some Other information";
}
And if you use this you have to change the for loop like this:
for (Actor actor : getWorld().getObjects(Rock.class)) {
    System.out.println(actor);
}
But you should declare the method toString because otherwhise there will just be some strange numbers or characters printet by the method.
Shawn Shawn

2013/3/17

#
Wow! Thanks! My friend suggested using arrays but he was unclear about it but yours is so easy! Lol I guess arrays are a bit far now
You need to login to post a reply.