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

问题描述 投票:2回答:4

而不是许多system.out.println行,我想在TestBook.java文件中编写System.out.println(b)。那么我应该在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 ("==================================");

    }

}
java eclipse-luna
4个回答
1
投票
  • 如果在OS X之前总是在* nix,Windows或Mac上消耗输出,则可以分别使用\n\r\n\r
  • 如果您希望代码与平台无关,并且您将在生成它的同一平台上使用数据,则可以使用String.format("%n")System.getProperty("line.separator")System.lineSeparator()

1
投票

您可以直接返回与要格式化的数据内联的换行符:

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

请注意,这可能是也可能不是解决此问题的最佳方法。


0
投票

这可能是我给出的最短的答案。

Google这个:

\n

0
投票

对于其他发生在这个问题上的人,同时可能尝试使用Eclipse的Source菜单项Generate toString()...和模板来做我过去一直在做的事情。我曾经尝试过这个模板: ${object.className} [\n${member.name()}=${member.value}, ${otherMembers}] 然而,这导致以下例如:

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

注意:“\ n”被替换为“\ n”,这显然在输出控制台或日志中没有用,所以我会快速搜索并替换以用单个替换双反斜杠。 随着一个新的eclipse工作区的开始和运行,我终于决定再次做一个快速的谷歌,并找出是否有更好的方法来做到这种情况我发现这个问题,但在找到它之前,我注意到了一个日食。 tostring templates的org链接所以我回到那个网页之后,这个问题的答案对我来说不合适,而且编辑模板就像是:

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

eclipse现在正确生成以下内容(我最后添加了一个标签以便清晰/格式化):

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

而且,这并没有完全回答OP的问题,因为他们手动创建了toString方法,但是它通过使用Eclipse的toString模板来实现或增强它,这可以节省大量时间,特别是如果你有20多个变量。 希望这可能有助于其他人

© www.soinside.com 2019 - 2024. All rights reserved.