-1

I just return to Java after few years, and I have a problem in traning app.

I want to add Book to class Library and I wrote that code:

public class Book{
    String author;
    String title;
    String code;
    int num;
    int num2;

    public Book(String author, String title, String code, int num, int num2) {
        this.author = author;
        this.title = title;
        this.code = code;
        this.num= num;
        this.num2= num2;
    }

Library:

import java.util.ArrayList;


public class Library{
    ArrayList<Book> books;

    public void AddBook(String a, String b, String c, int ab, int ac) {
        books.add(new Book(a,b,c,ab,ac));
            }

    public void showBooks(){
        System.out.println(books);
    }

    public static void main(String[] args) {

        Library l1 = new Library();
        l1.AddBook("Adad", "dasdasd", "asdasdasdas", 2121, 31);
        l1.showBooks();
    }
}

But I got NullPointException. It point line with AddBook method from Library class. I can't figure out it, even after research. I think it's a trival error, but I can't see it. Can someone who see my error, explain me what I wrote wrong?

martin
  • 1,145
  • 1
  • 7
  • 24

1 Answers1

4

This is because you never initialized your arraylist. Try this:

public class Library{
ArrayList<Book> books = new ArrayList<>();

public void AddBook(String a, String b, String c, int ab, int ac) {
    books.add(new Book(a,b,c,ab,ac));
}

public void showBooks(){
    System.out.println(books);
}

public static void main(String[] args) {

    Library l1 = new Library();
    l1.AddBook("Adad", "dasdasd", "asdasdasdas", 2121, 31);
    l1.showBooks();
}
}

And better practice is to code against the interface. So change this line:

List<Books> books = new ArrayList<>();

And also lowercase the first letter of the method to addBook(...)

Faraz
  • 6,025
  • 5
  • 31
  • 88