I am learning java and have been asked to create a 'Library' that stores books. Books should have a title, author and id. Which gets added using the method below addBook().
After the book is added, I want to be able to remove any book in the list that has a matching ID. If the ID matches it should be remove the title, author and ID from the array, not just the ID.
I have tried an number of different ways, including the solution below and looking at iterators. However, I only seem to be able to remove the ID of the book, or all the books in the lists!
I am learning, so I would be grateful for any solution to also explain why - I have been racking my head around it for days and I am super stuck!
Here is my code....
import java.util.ArrayList;
import java.util.Iterator;
/**
* Library class that represents a library
* where books will be stored.
*/
public class Library
{
// The list os books that is owned by the library
private ArrayList<Book> books;
// The name of the library
private String name;
/**
* Constructor for Library objects. This
* constructor sets the name of the library.
*/
public Library(String aName)
{
// Gives the library its name
name = aName;
// Initialises book field to an empty collection
books = new ArrayList<>();
}
/*
* Add a book to the library by adding its
* author, its title and and id.
*/
public void addBook(String author, String title, String id)
{
/** Add a new book to the Book list that
* includes its author, title and id
*/
books.add(new Book(author,title,id));
}
// Remove book from library
public void removeBook(String id)
{
for(Book book : books){
// When the ID given, matches an ID
// getId() is a getter method created in a seperate book class
if (book.getId() == id) {
// If that book is available
books.remove(book);
}
// If statements don't match, do nothing
else {
// Do nothing
}
}
}
}