제목, 저자 및 페이지 수를 세 개의 별도 열에 맞추려면 잘 모르겠습니다. 하지만이 작업을 수행 할 경우 책의 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 메서드에 대해이 작업을 수행 할 수 없습니다. –
당신은'String.format'을 사용할 것입니다. 그게 무슨 문제 야? –
"문자열 형식의 메서드 형식 (Locale, String, Object [])은 인수 (String, String, String, int)에 적용 할 수 없습니다." :( – user3764862