【发布时间】:2014-11-25 00:02:24
【问题描述】:
我的代码有一个大问题:
public class BookStore
{
private ArrayList<Book> books;
}
/**
* This method takes the author's name as a String parameter and returns an
* arraylist of all the books written by that author. It uses a while loop
* and an iterator, locates the books written by that author (case-insensitive)
* and adds them to another arraylist.
*/
public ArrayList<Book> getBooksByAuthor(String authorName){
ArrayList<Book> getBooksByAuthor = new ArrayList<Book>();
Iterator<Book> aBook = books.iterator();
while(aBook.hasNext()){
Book aBookd = aBook.next();
if (authorName.equalsIgnoreCase(aBookd.getAuthor())){
books.add(getAuthor());
books.addAll(getBooksByAuthor);
}
}
return getBooksByAuthor.size();
}
那三行
books.add(getAuthor());-
books.addAll(getBooksByAuthor);和 return getBooksByAuthor.size();
我很确定他们完全错了。我尝试了不同的方法来做到这一点,但没有奏效。我真的不明白该怎么做。有人可以帮助我吗?感谢您的宝贵时间!
【问题讨论】:
-
你试过运行这段代码吗?它从一个类开始,该类只定义了一个外部无法访问的数组列表,没有任何方法来操作该列表,以及一个与该类完全分离的函数。实际调用此函数并执行某些操作的其余代码在哪里?
-
看起来你只想用
getBooksByAuthor.add(aBookd);代替你提到的前两行。而且这段代码不会按原样编译——getBooksByAuthor.size();是一个int,你必须返回一个ArrayList<Book>——大概是getBooksByAuthor。无关紧要,你的命名很糟糕。