简体   繁体   English

如何在 java 的 toString() 方法中打印新行

[英]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.我想在 TestBook.java 文件中编写System.out.println(b)而不是许多system.out.println()行。 So what should I write in the toString() in the Book class to return the same results to look like below那么我应该在 Book 类的toString()中写什么来返回相同的结果,如下所示

//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.对于遇到这个问题的其他人,同时可能尝试使用 Eclipse 的源菜单项 Generate toString()... 使用模板来做我过去一直在做的事情。 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.注意: “\\n”被替换为“\\n”,这显然在输出控制台或日志中不起作用,所以我会进行快速搜索并替换以将双反斜杠替换为单个反斜杠。
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:随着一个新的 eclipse 工作区的启动和运行,我终于决定再次快速搜索谷歌并找出是否有更好的方法来做到这一点,在这种情况下我发现了这个 SO 问题,但是在找到它之前我注意到了一个日食。 tostring 模板的org 链接,所以在这个问题的答案对我来说离题后,我回到了那个网页,就像编辑模板一样简单:

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


And eclipse now properly generates the following (I did end up adding a tab for clarity/formatting): Eclipse 现在正确生成以下内容(为了清晰/格式,我最终添加了一个选项卡):

@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.再一次,这并不能完全回答 OP 的问题,因为他们手动创建了 toString 方法,但是它通过使用 Eclipse 的 toString 模板来做或增强它,这可以节省大量时间,尤其是当您有 20 多个变量时。

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如果在 OS X 之前的 *nix、Windows 或 Mac 上始终使用输出,则可以分别使用\\n\\r\\n\\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()如果您希望代码与平台无关,并且您将在生成它的同一平台上使用数据,则可以使用String.format("%n")System.getProperty("line.separator")System.lineSeparator()

This might be the shortest answer I have ever given.这可能是我给出的最短的答案。

Google This:谷歌这个:

\n

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

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