不知道我做错了什么因为我的toString()没有输出任何东西

时间:2016-09-04 04:01:21

标签: java stdout

我不知道为什么toString()无法正常工作。我试图搜索并找出答案,但我找不到任何东西。当我运行该程序时,它只是空白而且不输出任何内容。

这是我的司机班。

public static void main(String[] args) {        
    Telephone t1 = new Telephone(555,666,777, "mario");

    t1.toString();
}

电话类,省略了getter和setter方法。

public class Telephone {

    int areaCode, threeDigit, fourDigit;
    String userName;

    public Telephone(int areaCode, int threeDigit, int fourDigit, String userName) { 
        this.areaCode = areaCode;          
        this.threeDigit = threeDigit;       //constructor
        this.fourDigit = fourDigit;
        this.userName = userName;
    }

    public Telephone() {
        this.areaCode = 555;
        this.threeDigit = 555;            //default constructor
        this.fourDigit = 555;
        this.userName = null;
    }

    public Telephone(Telephone other) {
        areaCode = other.areaCode;
        threeDigit = other.threeDigit;           //copy constructor
        fourDigit = other.fourDigit;
        userName = other.userName;
    }


    public boolean equals(Telephone obj) {
        if (obj == this) {
            return true;
        } else if (!(obj instanceof Telephone)) {
            return false;
        } else
            return false;
    }

    public String toString(){

        String result = "The phone number of " + userName + "is: " + areaCode + 
        "-" + threeDigit + "-" + fourDigit;

        return result;
    }

}

我有一个要求,我应该使用toString()来输出语句。如果我没有这个要求,那么我就知道该怎么做,但在这种情况下我不知道。

2 个答案:

答案 0 :(得分:3)

调用toString不会向标准输出(stdout)写入任何内容。为此,您可以拨打System.out.println(String)。就像

一样
System.out.println(t1.toString());

答案 1 :(得分:0)

调用toString()不会导致标准输出。如果您希望这样做,请将public String toString(){ String result = "The phone number of " + userName + "is: " + areaCode + "-" + threeDigit + "-" + fourDigit; System.out.println(result); // Added line to print result return result; } 功能更改为:

main()

相反,如果您希望它返回字符串,然后在main()中打印,请尝试将public static void main(String[] args) { Telephone t1 = new Telephone(555,666,777, "mario"); System.out.println(t1.toString()); // Added line to print result } 更改为:

{{1}}