我正在尝试打印玩家类中的各个对象(性能,受伤和名称)以及主要类我尝试打印整个玩家对象但是当我尝试执行toString()时;两个班级的方法,我只收到玩家@ 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;
}
}
}
答案 0 :(得分:1)
最有可能的是,你只是忘了重新编译你的课程;你的Player
代码很好(你的Main
课程中有错误,你不知道,这表明没有重新编译)。也就是说,您发布的代码中没有任何内容可以实际打印任何内容。 System.out.println
(实际上,任何PrintWriter
打印方法)都会自动调用对象上的toString()
,因此无需自行调用,只需
System.out.println(player);
答案 1 :(得分:0)
使用
System.out.println(player.toString());
答案 2 :(得分:0)
toString()
返回对象的字符串/文本表示。 How to use the toString method in Java?
明确调用print,显示您的属性:
System.out.println(player.toString());
以及:
System.out.println(player);