【发布时间】:2021-01-18 21:44:52
【问题描述】:
我不知道如何编写我的toString() 方法。
这是我的 Main.java
Dice d = new Dice();
System.out.println(d);
d= new Dice(3);
System.out.println(d);
我的toString()方法应该怎么写,需要写两个toString()的吗?
我的Dice():
public class Dice {
private double kz= Math.random() * (6 - 1) + 1;
private double mz;
public Dice() {
this.kz= Math.random() * (6 - 1) + 1;
}
public Dice(double n) {
this.mz= n;
}
public String toString() {
return String.format("%.0f", this.kz);
}
}
这个我试过了,还是不行
public String toString(double i) {
return String.format("%.0f", this.mz);
}
【问题讨论】:
-
两个toString()是什么意思?
-
不清楚您期望带有参数的版本做什么,或者您为什么会这样写。但一般来说,要覆盖方法,您的方法需要与您要覆盖的方法具有相同的签名。从 Object.toString() 的定义中可以看出,这意味着没有参数。