我想知道如何格式化toString
:
我尝试使用printf
和tring.format
,但它希望我将String
和int
更改为Object[]
我希望它看起来像这样:(空格)
第一册______作者1 ________ 850
Book23 _____ Author2424 _____ 250
class Book
{
private String title,author;
private int numberOfPages;
Book()
{
}
public Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.numberOfPages = pages;
}
public String toString()
{
return(title + "%63s") + "\t" + (author + "%63s") + "\t" + numberOfPages;
// It actually works but makes the "%63s" appear :o
}
}
答案 0 :(得分:6)
return String.format("%-30s%-30s%10d", title, author, numberOfPages);
答案 1 :(得分:1)
String.format是正确的。您只需要将格式字符串设置为正确。
按如下方式更新toString()
方法:
public String toString()
{
return String.format("%63s\t%63s\t%10d", title, author, numberOfPages);
}
第一个%63s
将替换为title
。
%63s
将替换为author
并添加空格,使其超过标题末尾63个字符。
%10d
将替换为numberOfPages
,并将数字填充为10位数。
答案 2 :(得分:0)
我不确定您是否要将标题,作者和页数对齐在三个单独的列中。但是如果你这样做,你就无法通过覆盖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());
}
}
这个想法是查看哪个标题最长,并为每个要添加至少最长标题的填充的书添加。对于作者来说也是如此。
请注意,此代码编写得不是很好,但它应该足以传达这个想法。