toString方法

时间:2011-04-02 14:06:56

标签: java

  

可能重复:
  toString method

我被要求将print方法更改为toString方法,该方法在调用时显示完全相同的信息。我不知道如何将print方法的if语句放入tostring函数中。这是我们给出的原始课程。任何帮助表示赞赏!

 public class Item
 {
private String title;
private int playingTime;
private boolean gotIt;
private String comment;

/**
 * Initialise the fields of the item.
 * @param theTitle The title of this item.
 * @param time The running time of this item.
 */
public Item(String theTitle, int time)
{
    title = theTitle;
    playingTime = time;
    gotIt = false;
    comment = "<no comment>";
}

/**
 * Enter a comment for this item.
 * @param comment The comment to be entered.
 */
public void setComment(String comment)
{
    this.comment = comment;
}

/**
 * @return The comment for this item.
 */
public String getComment()
{
    return comment;
}

/**
 * Set the flag indicating whether we own this item.
 * @param ownIt true if we own the item, false otherwise.
 */
public void setOwn(boolean ownIt)
{
    gotIt = ownIt;
}

/**
 * @return Information whether we own a copy of this item.
 */
public boolean getOwn()
{
    return gotIt;
}




    /**
 * Print details of this item to the text terminal.
 */
public void print()
{
    System.out.print(title + " (" + playingTime + " mins)");
    if(gotIt) {
        System.out.println("*");
    } else {
        System.out.println();
    }
    System.out.println("    " + comment);
}

}

2 个答案:

答案 0 :(得分:2)

toString()方法只是一个方法,就像任何其他一样。它只需要返回一个String。

转换现有的print()方法:

  1. 将其重命名为toString()
  2. 声明它返回String
  3. 使用StringBuilder在方法中构建字符串,并在其上调用toString()以获取返回值

答案 1 :(得分:2)

这不是最有效或最好的方法,但它很容易理解。它非常类似print()函数。更简单的方法是使用下面的toString方法。

public void print()
{
    System.out.print(title + " (" + playingTime + " mins)");
    if(gotIt) {
        System.out.println("*");
    } else {
        System.out.println();
    }
    System.out.println("    " + comment);
}
@Override
public String toString()
{
    String r = title + " (" + playingTime + " mins)";
    if(gotIt) {
        r = r + "*\n";
    } else {
        r = r + "\n";
    }
    r = r + "    " + comment;
    return r;
}
public void print2()
{
    System.out.println( this.toString() );
}