1

这是另外两个类的驱动方法。我在这里发布 https://codereview.stackexchange.com/questions/33148/book-program-with-arraylist

我需要一些关于私有静态 ArrayList getAuthors(String authors) 方法的帮助。我是个初学者。所以请帮我完成这个驱动方法。或者给我一些指示。

操作说明

allAuthors 数组的一些元素在两个作者姓名之间包含星号“*”。getAuthors 方法使用此星号作为名称之间的分隔符,以将它们分别存储在返回的字符串数组列表中。

import java.util.ArrayList;

public class LibraryDrive {

public static void main(String[] args) {

    String[] titles = { "The Hobbit", "Acer Dumpling", "A Christmas Carol",
            "Marley and Me", "Building Java Programs",
    "Java, How to Program" };

    String[] allAuthors = { "Tolkien, J.R.", "Doofus, Robert",
            "Dickens, Charles", "Remember, SomeoneIdont",
            "Reges, Stuart*Stepp, Marty", "Deitel, Paul*Deitel, Harvery" };

    ArrayList<String> authors = new ArrayList<String>();
    ArrayList<Book> books = new ArrayList<Book>();

    for (int i = 0; i < titles.length; i++) {
        authors = getAuthors(allAuthors[i]);
        Book b = new Book(titles[i], authors);
        books.add(b);
        authors.remove(0);
    }
    Library lib = new Library(books);
    System.out.println(lib);
    lib.sort();
    System.out.println(lib);

}

private static ArrayList<String> getAuthors(String authors) {
    ArrayList books = new ArrayList<String>();
            // need help here.
    return books;
}

}
4

5 回答 5

5

尝试这个

private static ArrayList<String> getAuthors(String authors) {
    ArrayList books = new ArrayList<String>();
      String[] splitStr = authors.split("\\*");
      for (int i=0;i<splitStr.length;i++) {
        books.add(splitStr[i]);
       }
    return books;
}
于 2013-10-24T09:53:23.017 回答
1

我建议String.split在这里使用(但请记住,此方法使用正则表达式作为参数):

private static ArrayList<String> getAuthors(String authors) {
    ArrayList books = new ArrayList<String>();
    String[] strgArray = authors.split("\\*"); 
    books.addAll(Arrays.asList(strgArray));
    return books;
}

或者

private static ArrayList<String> getAuthors(String authors) {
    String[] strgArray = authors.split("\\*"); 
    ArrayList books = Arrays.asList(strgArray);
    return books;
}
于 2013-10-24T10:04:56.860 回答
1

试试这个,但实际上我不明白为什么要删除ArrayListfor 循环中的零索引元素。

private static ArrayList<String> getAuthors(String authors) {
    ArrayList<String> array = new ArrayList<String>();
    String[] authorsArray = authors.split("\\*");
    for(String names : authorsArray );
        array.add(names);
    return array;
}
于 2013-10-24T09:58:24.723 回答
0

看看String#split方法,这将帮助你用星号分隔作者。此方法返回一个数组,因此您需要检查该数组中有多少作者,然后将每个作者存储到ArrayList.

于 2013-10-24T09:50:56.900 回答
0

以下是您可以如何去做。

  1. authors根据星号将您获得的字符串拆分为方法参数。(使用String.split(delim)方法)
  2. 生成的 string[] 数组需要使用for循环进行迭代,并且每个迭代的元素都应该添加到您的列表中。(使用List.add(elem)方法)
  3. 完成后,返回该列表(您已经这样做了)。

既然知道怎么做,就需要自己实现代码了。

于 2013-10-24T09:52:14.177 回答