我想在 TestBook.java 文件中编写 System.out.println(b)
,而不是许多 system.out.println()
行。
那么我应该在 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 ("==================================");
}
}
最佳答案
对于遇到这个问题的其他人,同时可能尝试做我过去一直在做的事情,使用 Eclipse 的源菜单项 Generate toString()... 和模板。我曾经尝试将其作为模板:
${object.className} [\n${member.name()}=${member.value}, ${otherMembers}]
但是,这导致了以下示例:
@Override
public String toString() {
return "NEDCustomer [\\nsubscriberType=" + subscriberType + "]";
注意:“\n”被替换为“\n”,这显然在输出控制台或日志中不起作用,所以我会进行快速搜索并替换以用单个反斜杠替换双反斜杠.
随着新的 eclipse 工作区的启动和运行,我最终决定再次快速谷歌一下,看看是否有更好的方法,在这种情况下,我发现了这个 SO 问题,但是在找到它之前,我注意到了一个 eclipse。 tostring templates 的组织链接所以在这个问题的答案对我来说不是主题之后我回到了那个网页,它就像编辑模板一样简单,而不是:
${object.className} [
${member.name()}=${member.value},
${otherMembers}]
现在 eclipse 正确地生成了以下内容(为了清晰/格式化,我最终添加了一个选项卡):
@Override
public String toString() {
return "NEDCustomer [\n\tsubscriberType=" + subscriberType + "]";
再说一次,这并不能完全回答 OP 的问题,因为他们手动创建了 toString 方法,但是通过使用 Eclipse 的 toString 模板可以节省大量时间,特别是如果您有 20 个以上的变量,它会以某种方式做到或增强它。
希望这可能对其他人有帮助
关于java - 如何在 java 的 toString() 方法中打印新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29038627/