繁体   English   中英

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方法就不需要尝试弄清楚 object 是如何构造的:

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 类调用的默认方法,它是将 object 信息作为字符串返回的标准。

你的方法:

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

不起作用,因为按照惯例,像Stystem.out.println()这样的方法会寻找标准签名,而不是奇怪的toString(doulbe foo)

如果您想在方法调用中查看 object state,您可以执行以下操作:

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

您可以对 Dice class 进行一些调整:

  • 你也可以省略 this 关键字,当你想引用你所在的同一个 object 或者有这样的冲突时,你必须使用:
     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; } }
  • 您只能拥有一个变量和多个自己调用的构造函数(归功于Mureinik 的回答):
     public class Dice { private double kz; public Dice() { this(Math.random() * (6 - 1) + 1); } public Dice(double n) { this.kz = n; } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM