2014-11-25 110 views
-2

我有我的代码一个巨大的问题:在Java中另一个ArrayList中添加的ArrayList与迭​​代

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();

我很确定他们是完全错误的。我尝试了不同的方式来做到这一点,但它没有奏效。我真的不明白该怎么做。有人能帮助我吗?感谢您的时间!

+0

你试过运行此代码?它从一个类开始,只定义了一个不可访问的外部数组列表,没有任何方法来操纵该列表,以及一个完全脱离类的函数。代码的其余部分实际调用此函数并执行某些操作的位置在哪里? – 2014-11-25 00:07:04

+0

看起来你只是想'getBooksByAuthor.add(aBookd);'代替你提到的前两行。并且这段代码不会按原样编译 - “getBooksByAuthor.size();'是一个'int',你必须返回一个'ArrayList ' - 大概是'getBooksByAuthor'。无关地,你的命名是残酷的。 – drewmoore 2014-11-25 00:07:13

回答

0

我相当肯定你想添加与匹配作者的名字的书籍到一个新的列表。一些与使用for-each loop

List<Book> al = new ArrayList<>(); 
for (Book book : books) { 
    if (authorName.equalsIgnoreCase(book.getAuthor())) { 
     al.add(book);  
    } 
} 
return al; 

或使用一个明确的Iterator

List<Book> al = new ArrayList<>(); 
Iterator<Book> iter = books.iterator(); 
while (iter.hasNext()) { 
    Book book = iter.next(); 
    if (authorName.equalsIgnoreCase(book.getAuthor())) { 
     al.add(book); 
    } 
} 
return al; 
+0

它有用!感谢您的时间。 – user3040075 2014-11-25 00:37:21

0

是有迭代器和一个while循环而不是foreach循环的任何具体需要一个隐含的迭代器?

什么(我认为)你想达到的是正常的语言是:我们有一个空的收集/列表作为结果。对于书籍列表中的每本书,检查作者是否具有与给定名称相同的名称 - 如果名称相同,我们将该书添加到结果集合/列表中。

,在代码如下:

public ArrayList<String> getBooksByAuthor(String authorName) { 
    ArrayList<Book> result = new ArrayList<Book>(); 
    for (Book aBook : books) { //[for each notation in java ][1] 
     if (authorName.equals(aBook.getAuthor())) { 
      result.add(aBook); 
     } 
    } 
    return result; 
} 

,如果你想使用while循环,阅读起来的foreach /而在this link循环转换。

除了

,并在评论中提到,你的代码有一些语义和句法错误:

  • 您的返回类型是错误的(INT而不是ArrayList的)你之前
  • 类定义右括号结束方法定义
  • 你author对象(可能是一个字符串)添加到您的图书收集
  • 你从来没有任何一本书添加到您的集合中
  • 您尝试(空)收集getBooksByAuthoraddAll对象,以你的书,而不是添加一些/单书你getBooksByAuthor收集

    [1] http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

+0

非常感谢!我会看看你的链接。 – user3040075 2014-11-25 00:35:56

相关问题