简体   繁体   中英

Trying to print object through toString()

I am trying to print the individual objects in the players class(performance, injured and name) and on the main class I am trying to print the entire player object however when I try executing the toString(); method on both classes, I just receive player@2eb3998c or Main@37e6e526. Where am I going wrong?

Thanks for any help.

Player class:

  package com.laurens;

/**
* Created by laurensvanoorschot on 20-01-16.
*/
 public class player {
 private String name;
 private int performance;
 private boolean injured;

    public  player(int performance, boolean injured, String name) {
    this.injured = injured;
    this.name = name;
    this.performance = performance;
}

public boolean isInjured() {
    return injured;
}

public void setInjured(boolean injured) {
    this.injured = injured;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getPerformance() {
    return performance;
}

public void setPerformance(int performance) {
    this.performance = performance;
}

@Override
public String toString() {
    return "com.laurens.player{" +
            "injured=" + injured +
            ", name='" + name + '\'' +
            ", performance=" + performance +
            '}';
}
 }

main Class:

  package com.laurens;
  public class Main {
    private player player;
   public static void main(String[] args) {
    player player = new player (4, true, "laurens");
    player.toString();
}


public com.laurens.player getPlayer() {
    return player;
}

@Override
public String toString() {
    return super.toString();
}

public void setPlayer (int performance, String name) {
    if (performance < 4) {

        boolean injured = true;


    }



}
}

Most likely, you simply forgot to recompile your classes; your Player code is fine (and you have errors in your Main class that you aren't aware of, which suggests no recompile). That said, there's nothing in your posted code that actually prints anything . System.out.println (actually, any PrintWriter print methods) will automatically call toString() on an object, so there's no need to do that yourself, just

System.out.println(player);

采用

System.out.println(player.toString());

toString() returns a string/textual representation of the object. How to use the toString method in Java?

Explicitly calling print, displays your properties fine:

System.out.println(player.toString());

as well as:

System.out.println(player);

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