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

2019/2/16

Getting names of objects to print for debugging purposes

MRCampbell MRCampbell

2019/2/16

#
I want to get information to print to the terminal about a specific object, but I can't tell which instance of the object the information is coming from. What I want this code to print is: cat1: current X:1106 OR cat2: current X:1106 This is what is printing: CatClass: current X:1106 This code is where I create the objects in a subclass of world.
CatClass cat1 = new CatClass();
CatClass cat2 = new CatClass();
    
    public void populateAlly()
    {
        addObject(cat1, 1600, 247);
        addObject(cat2, 3750, 247);        
    }
This is a line of code in the act method of the CatClass.
System.out.println(getClass().getName() + ": current X: " + getX()); 
danpost danpost

2019/2/17

#
MRCampbell wrote...
I want to get information to print to the terminal about a specific object, but I can't tell which instance of the object the information is coming from.
Introduce an indentifying field into the CatClass class:
private String name;
Then add a constructor to the class to accept a name:
public CatClass(String id)
{
    name = id;
}
Now, you can give the cats their names:
CatClass cat1 = new CatClass("cat1");
CatClass cat2 = new CatClass("cat2");
For the print line command, you can now use:
System.out.println(name + ": current X :"+ getX());
You need to login to post a reply.