having some problem with my school work, and hope i can get some help here! Apparently there’s a nullpointerexception error at line 17.
import java.util.*;
import java.text.*;
public class Librarian {
private ArrayList<Book> bookList = new ArrayList<Book>();
public Librarian() {
bookList = new ArrayList<Book>();
}
public ArrayList<Book> findBooksWrittenBy(ArrayList<Book> bookList, String author) {
ArrayList<Book> booksByAuthor = new ArrayList<Book>();
for(int i = 0; i < bookList.size(); i++) {
Book book = bookList.get(i);
String author1 = book.getAuthor();
if(author1.equalsIgnoreCase(author)) {
booksByAuthor.add(book);
}
if(booksByAuthor.size() != 0) {
booksByAuthor = booksByAuthor;
}else {
booksByAuthor = null;
}
}
return booksByAuthor;
}
Place your check on authors outside of the for loop.
Then, check for size and return immediately, it is redundant to assign an object to itself.
As follows: