我的任务是创建5个图书对象并存储在一个数组中,我没有问题!我能够使用println打印出对象的变量没问题,但是当我希望能够使用printf移动变量时,我不知道如何调用数组某个元素的特定变量。请帮助!
public class BookReport {
public static void main(String[] args){
Book[] TheBooks = new Book[5] ;
TheBooks[0] = new Book("Gone With The Wild", "Paul Mitchell", 1000) ;
TheBooks[1] = new Book("Harry Toilet", "Donald Trump", 100) ;
TheBooks[2] = new Book("Huckles Finn Berry", "SpiderMan", 500) ;
TheBooks[3] = new Book("The Bad Habbit", "Nose Picker", 700) ;
TheBooks[4] = new Book("Alien", "Mister Green", 600) ;
System.out.printf("%10s %20s %18s \n", "Book Title" , "Author", "Pages") ;
System.out.printf("%s \n", "----------------------------------------------------") ;
//This works but I cant justify the variables to align!!!
System.out.println(TheBooks[0]) ;
}
}
public class Book {
private String title = "" ;
private String author = "" ;
private int pages = 0 ;
public Book(String title, String author, int pages){
setTitle(title) ;
setAuthor(author) ;
setPages(pages) ;
}
public String getTitle(){
return title ;
}
public String getAuthor(){
return author ;
}
public int getPages(){
return pages ;
}
public void setTitle(String newTitle){
title = newTitle ;
}
public void setAuthor(String newAuthor){
author = newAuthor ;
}
public void setPages(int newPages){
pages = newPages ;
}
public String toString(){
return title + " " + author + " " + pages ;
}
public boolean equals(Book anotherBook){
return ((title.equals(anotherBook.title)) && (author.equals (anotherBook.author)) &&
(pages == anotherBook.pages)) ;
}
}
答案 0 :(得分:0)
只需为要打印的各个字段调用getter:
System.out.printf("%10s %20s %18s \n", "Book Title" , "Author", "Pages");
System.out.printf("%s \n", "----------------------------------------------------") ;
for (Book b : TheBooks) {
System.out.printf("%10s %20s %18s \n", b.getTitle(), b.getAuthor(), b.getPages());
}
顺便说一下,您将书籍数组命名为TheBooks
,但不是将大写字母作为首字母命名为变量的Java约定。所以theBooks
在这里会更好。
答案 1 :(得分:0)
如果要调用数组中某个元素的特定变量。 你可以用
java.util.Map
例如,您可以为要存储的所有对象设置 ID 。
HashMap<String, Book> h = new HashMap<>();
Book book = new Book("Gone With The Wild", "Paul Mitchell", 1000);
h.put(book.getTitle(), book);
book = new Book("Harry Toilet", "Donald Trump", 100);
h.put(book.getTitle(), book);
book = new Book("Huckles Finn Berry", "SpiderMan", 500);
h.put(book.getTitle(), book);
book = new Book("The Bad Habbit", "Nose Picker", 700);
h.put(book.getTitle(), book);
book = new Book("Alien", "Mister Green", 600);
h.put(book.getTitle(), book);
// if you want to call it
Book b = h.get("exampletitle);
答案 2 :(得分:0)
您还应该能够在toString方法中使用String.format(),以便拥有可重复使用的格式化版本。
@Override
public String toString(){
return String.format("%10s %20s %18s \n", title, author, pages);
}
P.S。我认为在包含equals()的类中包含hashCode()是一种好习惯。