Java 带参数和不带参数的toString()

Java 带参数和不带参数的toString(),java,tostring,Java,Tostring,我不知道如何编写我的toString()方法 这是我的Main.java Dice d = new Dice(); System.out.println(d); d= new Dice(3); System.out.println(d); 我应该如何编写我的toString()方法,我是否需要编写两个toString() 我的骰子(): 我用这个试过了,但没用 public String toString(double i) { return String.format("

我不知道如何编写我的
toString()
方法

这是我的Main.java

Dice d = new Dice();
System.out.println(d);

d= new Dice(3);
System.out.println(d);
我应该如何编写我的
toString()
方法,我是否需要编写两个toString()

我的
骰子()

我用这个试过了,但没用

public String toString(double i) {
    return String.format("%.0f", this.mz);
}

您可以使用同一个成员,而不是为两个构造函数使用两个单独的成员。这样,您的
toString
方法就不需要尝试找出对象是如何构造的:

公共类骰子{
私人双kz;
公众骰子(){
这(Math.random()*(6-1)+1);
}
公共骰子(双n){
这是kz=n;
}
公共字符串toString(){
返回字符串.format(“%.0f”,this.kz);
}
}
toString()方法是大多数内置java类调用的默认方法,它是以字符串形式返回对象信息的标准方法

您的方法:

public String toString(double i) {
    return String.format("%.0f", this.mz);
}
不起作用,因为按照惯例,像
Stystem.out.println()
这样的方法将查找标准签名,而不是奇怪的
toString(doulbe-foo)

如果要在方法调用时查看对象状态,可以执行以下操作:

public String toString(double i) {
    return String.format("kz = %.0f, mz = %.0f, ", kz, mz);
}
您可以对骰子类进行一些调整:

  • 您还可以省略this关键字,当您要引用所处的同一对象或存在如下冲突时,必须使用该关键字:
    public class Dice {
    
        private double foo;
    
        // If you try to remove this. you will get a runtime error
        public Dice(double foo) {
            this.foo = foo;
        }
    }
    
  • 您只能有一个变量和多个构造函数调用自己(请注意):

two-toString()是什么意思?不清楚您希望带参数的版本做什么,也不清楚您为什么会这样写。但一般来说,要重写一个方法,您的方法需要与您要重写的方法具有相同的签名。从Object.toString()的定义中可以看出,这意味着没有参数。
public class Dice {

    private double foo;

    // If you try to remove this. you will get a runtime error
    public Dice(double foo) {
        this.foo = foo;
    }
}
public class Dice {
    private double kz;

    public Dice() {
        this(Math.random() * (6 - 1) + 1);
    }

    public Dice(double n) {
        this.kz = n;
    }
}