toString() 带参数和不带参数

toString() with and without parameter

我不知道如何编写我的 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 方法就不需要尝试弄清楚对象是如何构造的:

public class Dice {

    private double kz;

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

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

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

toString() 方法是大多数内置 java classes 调用的默认方法,它是将对象信息作为字符串返回的标准。

你的方法:

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);
}

您可以对您的骰子进行一些调整 class:

  • 你也可以省略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;
        }
    }
    
  • 您只能有一个变量和多个调用自身的构造函数(归功于 ):
    public class Dice {
        private double kz;
    
        public Dice() {
            this(Math.random() * (6 - 1) + 1);
        }
    
        public Dice(double n) {
            this.kz = n;
        }
    }