简体   繁体   中英

How can I print a new line in a toString() method in java

Instead of the many system.out.println() lines, I want to write System.out.println(b) in TestBook.java file. So what should I write in the toString() in the Book class to return the same results to look like below

//Title: xxx
//Author:xxx
//Years:xxx
//Pages:xxx
//edition: xxxx
//==================================

public class Book {

String title;
String author;
int yearOfPublishing;
int numberOfPages;
int eddition;

Book ()
{}

Book ( String title, String author, int yop, int nop, int eddition)
{
    this.title = title;
    this.author = author;
    yearOfPublishing = yop;
    numberOfPages = nop;
    this.eddition = eddition;

}

public String toString()
    {
    // return what?? how can i return new lines
    }
}

public class TestBook {

    public static void main(String[] args) {

        Book b = new Book("Data", "Joe", 2015, 276, 3);

        System.out.println ( "Title : " +b.title);
        System.out.println ( "Author : " +b.author);
        System.out.println ( "Year : " +b.yearOfPublishing);
        System.out.println ( "Pages : " +b.numberOfPages);
        System.out.println ( "Eddition : " +b.eddition);    
        System.out.println ("==================================");

    }
}

For others that happen across this question while possibly trying to do what I had been doing in the past using Eclipse's Source menu item Generate toString()... with a template. I used to try this as the template:
${object.className} [\\n${member.name()}=${member.value}, ${otherMembers}]

However that resulted in the following for example:

@Override
public String toString() {
    return "NEDCustomer [\\nsubscriberType=" + subscriberType + "]";


Note: the "\\n" was replaced with "\\n" which obviously didnt work in the output console or log so then I'd do a quick search and replace to replace the double backslash with a single.
With a new eclipse workspace up and going, I finally decided to do a quick google once again and find out if there was a better way to do it in which case I found this SO question, however prior to finding it I noticed an eclipse.org link of tostring templates so I went back to that web page after this questions answers were off topic for me and it was as simple as editing the template to instead be:

${object.className} [
    ${member.name()}=${member.value}, 
    ${otherMembers}]


And eclipse now properly generates the following (I did end up adding a tab for clarity/formatting):

@Override
public String toString() {
    return "NEDCustomer [\n\tsubscriberType=" + subscriberType + "]";


And again, this doesnt totally answer the OP's question as they were manually creating the toString method however in a way it does or enhances it by using Eclipse's toString template which can save considerable time especially if you have 20+ variables.

Hope this possibly helps others

You can just return newline characters inline with the data you want to format:

return "Title : " + title + "\nAuthor : " + author ...

Note that this may or may not be the best approach to this problem.

  • If the output will always be always consumed on *nix, Windows or Mac prior to OS X, you can respectively use \\n , \\r\\n or \\r
  • If you want the code to be platform independent and you will consume the data on the same platform on which it is produced, you can use String.format("%n") , System.getProperty("line.separator") or System.lineSeparator()

This might be the shortest answer I have ever given.

Google This:

\n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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