gpt4 book ai didi

java - 尝试通过 toString() 打印对象

转载 作者:行者123 更新时间:2023-12-01 10:33:33 26 4
gpt4 key购买 nike

我试图打印玩家类中的各个对象(表现、受伤和姓名),并且在主类上我试图打印整个玩家对象,但是当我尝试执行 toString(); 时两个类上的方法,我只收到player@2eb3998c 或Main@37e6e526。我哪里出错了?

感谢您的帮助。

玩家等级:

  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 +
'}';
}
}

主类:

  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;


}



}
}

最佳答案

很可能,您只是忘记重新编译您的类;您的 Player 代码没有问题(并且您的 Main 类中存在您不知道的错误,这表明无需重新编译)。也就是说,您发布的代码中没有任何内容实际打印任何内容System.out.println(实际上,任何 PrintWriter 打印方法)都会自动调用对象上的 toString(),因此无需执行任何操作你自己,只是

System.out.println(player);

关于java - 尝试通过 toString() 打印对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34951468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com