开发者

toString method [duplicate]

开发者 https://www.devze.com 2023-02-21 06:58 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: toString method I have been asked to change the print method into a toString method that displays the exa
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

toString method

I have been asked to change the print method into a toString method that displays the exact same information when called. I'm not sure how i can put the if statements of the print method into the tostring function. Here is the original class we have been given. any help is appreciated!

 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开发者_如何学Python(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);
}

}


The toString() method is simply a method like any other. It just has to return a String.

To convert your existing print() method:

  1. rename it to toString()
  2. declare it to return a String
  3. build the string in the method using a StringBuilder and call toString() on that to get your return value


This is not the most efficient or best way to do it, but it is easy to understand. It resembles the print() function quite a lot. The easier way to do it is the toString method below.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号