简体   繁体   中英

Printing a variable's name as a String, Or linking a variable to a String Variable to be 'printed'

I am trying to create a simple chess game. I currently have all the chess pieces on a 2d array. They are each named BP1, BP2 (black pawn 1 & 2) , BK (Blacking) and etc...

My question is:

How do I print these "GamePiece" Types I have created (with each type of piece extended to its own class) on the screen? Or perhaps I should link these variables to a String variable to be printed on the console? The current method I have only prints the addresses.

You have to override public String toString() for each of the classes of the objects you wish to print. What you actually return in that method is entirely up to you.

Every Object in Java has a default toString() method which returns the address of the variable and I think this is what you are seeing. In order to correct that you need to override the toString() method in your class and implement it so that it returns what you need it to. For example if you want to return the name it should be something like this:

public String toString(){
    return name;
}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM