Frage

I have an array of JLabel PlayerLabel and array of PlayerName which is intialised the following way

        String [] PlayerName;
        PlayerName = new String[4];
        for (int i=0;i<4;i++)
        {
            PlayerName[i] = "None1";

        }

JLabel [] PlayerLabel;

PlayerLabel = new JLabel[4];

        for (int i=0;i<4;i++)
        {
            String num = Integer.toString(i);
            String output = "Player " + num + " : " + PlayerName;

            PlayerLabel[i] = new JLabel(output);
            PlayerLabel[i].setForeground(Color.white);

        }

I would expect the text of my JLabel to be

Player 1 : None1

Instead I am getting

Player 1 : java.lang.String;@4e9fd887

the @15150ef8part changes to a different combination of numbers and letters everytime i restart the program .

The PlayerName is alright when i initialised it enter image description here

I have no idea why the PlayerName becomes weird when it is added at output

enter image description here

What is happening , How do i resolve this issue ??

War es hilfreich?

Lösung

When you do + Playername, you're printing the array itself, not an element in the array. When you try to concatenate an object to a string, the object's toString() method is called, and arrays inherit their toString() from Object:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

And that's probably not what you wanted.

You might have wanted to do Playername[i].

Andere Tipps

This will print the certain element of the array at the end of your string:

String output = "Player " + num + " : " + PlayerName[i];
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top