我不太確定您是否希望將標題,作者和頁數以三個單獨的列對齊。但是,如果你這樣做,你不能通過重寫Book的toString
方法來實現這一點,因爲它不知道集合中其他書籍的標題和作者名稱有多長。
但是,您可以爲書籍聲明自定義集合並覆蓋其toString
方法。這可能如下所示:
class Main {
static class Book
{
private String title,author;
private int numberOfPages;
public Book(String title,String author,int pages) {
this.title = title;
this.author = author;
this.numberOfPages = pages;
}
public String toString()
{
return String.format("%-30s%-30s%10d", title, author, numberOfPages);
}
}
static class Library {
public static final int Margin = 2;
private List<Book> books = new ArrayList<Book>();
public void addBook(Book book){
books.add(book);
}
private int longestTitle() {
int result = 0;
for (Book book : books) {
result = book.title.length() > result ? book.title.length() : result;
}
return result;
}
private int longestAuthor() {
int result = 0;
for (Book book : books) {
result = book.author.length() > result ? book.author.length() : result;
}
return result;
}
public String toString() {
String result = "";
for (Book book : books) {
int titleLength = book.title.length();
result += book.title;
for (int i = longestTitle(); i > titleLength - Margin; i--){
result += " ";
}
result += book.author;
int authorLength = book.author.length();
for (int i = longestAuthor(); i > authorLength - Margin; i--){
result += " ";
}
result += book.numberOfPages + "\n";
}
return result;
}
}
public static void main(String[] args) {
Library lib = new Library();
Book b1 = new Book("Knights of the round table", "King Arthur", 123);
lib.addBook(b1);
Book b2 = new Book("It", "Stephen King", 1345);
lib.addBook(b2);
Book b3 = new Book("A very, very, very, very long title that seems pointless", "Me", 112);
lib.addBook(b3);
// System.out.println(b1);
// System.out.println(b2);
// System.out.println(b3);
// They do not align separately
System.out.println(lib.toString());
}
}
的想法是看其標題是最長的,並添加你想要打印至少達到最長的標題填充每一本書。作者也一樣。
請注意,這段代碼寫得不是很好,但它應該足以表達這個想法。
'%63s'只是您連接的字符串文字。這些標籤是由'「\ t」'添加的,因此您可以簡單地刪除'%63s',但如果您的書名和作者長度不同,這很可能不會對齊。編輯:你想讓書籍集合一致嗎?如果是這樣,你不能爲個別的toString方法做到這一點。 – 2014-09-25 22:18:14
你應該使用'String.format'。有什麼問題? – 2014-09-25 22:22:59
「String類型的方法格式(Locale,String,Object [])不適用於參數(String,String,String,int)」 :( – user3764862 2014-09-25 22:27:29