2014-09-25 2 views
1
내가 toString 포맷하는 방법을 알고 싶습니다

: 나는 printf과의 tring.format를 사용하여 시도하지만 제가이 같이 할 Object[]포맷 toString 자바

Stringint을 변경하고자 을 (스페이스)

Book1______Author1________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 
    } 
} 
+2

'% 63s'은 연결하는 문자열 리터럴입니다. 탭은''\ t "'에 의해 추가되므로'% 63s '을 간단하게 제거 할 수 있습니다. 그러나 책 제목과 저자가 다른 길이라면 정렬되지 않을 가능성이 높습니다. 편집 : 도서 컬렉션을 정렬하려고? 그렇다면 개별 toString 메서드에 대해이 작업을 수행 할 수 없습니다. –

+0

당신은'String.format'을 사용할 것입니다. 그게 무슨 문제 야? –

+0

"문자열 형식의 메서드 형식 (Locale, String, Object [])은 인수 (String, String, String, int)에 적용 할 수 없습니다." :( – user3764862

답변

5
return String.format("%-30s%-30s%10d", title, author, numberOfPages); 
+0

이미 시도했습니다. "The (String, String, String, int) 인수에 메서드 형식 (Locale, String, Object [])을 사용할 수 없습니다 :/ – user3764862

+0

@ user3764862 사용중인 Java 버전은 무엇입니까? – Brian

+2

http : // ideone .com/fork/khe1Wc – maszter

0

및 String.format 올바른 것입니다. 형식 지정 문자열을 올바르게 가져와야합니다.

업데이트합니다 toString() 방법을 다음과 같이이 :

public String toString() 
{ 
    return String.format("%63s\t%63s\t%10d", title, author, numberOfPages); 
} 

첫 번째 %63stitle로 대체됩니다.

%63sauthor으로 바뀌고 공백을 추가하여 제목 끝에 63자를 넘깁니다.

%10dnumberOfPages으로 바뀌며 10 자리로 번호가 채워집니다.

0

제목, 저자 및 페이지 수를 세 개의 별도 열에 맞추려면 잘 모르겠습니다. 하지만이 작업을 수행 할 경우 책의 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()); 
} 

} 

아이디어는 가장 긴 인 제목을보고 당신이 적어도 가장 긴 제목에 도달 패딩을 인쇄 할 각 책을 추가하는 것입니다 : 다음과 같이 보일 수있다. 저자에게도 마찬가지입니다.

이 코드는 실제로 잘 작성되지 않았지만 아이디어를 전달하는 데 충분해야합니다.