[英]How can I print a new line in a toString() method in java
我想在 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 問題,但是在找到它之前我注意到了一個日食。 tostring 模板的org 鏈接,所以在這個問題的答案對我來說離題后,我回到了那個網頁,就像編輯模板一樣簡單:
${object.className} [
${member.name()}=${member.value},
${otherMembers}]
Eclipse 現在正確生成以下內容(為了清晰/格式,我最終添加了一個選項卡):
@Override
public String toString() {
return "NEDCustomer [\n\tsubscriberType=" + subscriberType + "]";
再一次,這並不能完全回答 OP 的問題,因為他們手動創建了 toString 方法,但是它通過使用 Eclipse 的 toString 模板來做或增強它,這可以節省大量時間,尤其是當您有 20 多個變量時。
希望這可能對其他人有幫助
您可以只返回與要格式化的數據內聯的換行符:
return "Title : " + title + "\nAuthor : " + author ...
請注意,這可能是也可能不是解決此問題的最佳方法。
\\n
、 \\r\\n
或\\r
String.format("%n")
、 System.getProperty("line.separator")
或System.lineSeparator()
這可能是我給出的最短的答案。
谷歌這個:
\n
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.