Seems you got confused with what the expression you're evaluating in the IF statement is doing. You're if
expression effectively says: "if bookTitle matches one in bookList (ie. is a duplicate)" Do X, else Y.
The "do X" branch says "Add the book" booklist.add(bookTitle)
- when its a duplicate - which is wrong.
The "do Y" branch of your if
says (corrected syntax): System.out.println("This book is not unique");
which has no effect on the bookList
Instead I've swapped the two branches X
and Y
-> Y
and X
So you should have:
public void addBook(Book bookTitle){
for(Book bookId : bookList) {
if (bookTitle.equals(bookId)) {
System.out.println("This book is not unique");
break; // breaks out of the surrounding for-loop
// stop checking books if we enter this branch
} else {
bookList.add(bookTitle);
System.out.println("Book registered.");
// keep checking more books if we enter this branch
}
}
}
Research tells us the more nested our code is the more likely it is for bugs to occur as the logic is harder to digest.
I've had a go at breaking it all apart and came up with:
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
class LibraryApplication {
static Library library;
public static void main(String[] args) {
library = new Library();
addBook(new Book("Title 1"));
addBook(new Book("Title 1"));
addBook(new Book("Title 2"));
library.printAllBooks();
}
public static void addBook(Book bookTitle){
if (library.isBookInLibrary(bookTitle)) {
System.out.println("This book (" + bookTitle.getTitle() + ") is not unique");
} else {
library.add(bookTitle);
System.out.println("Book " + bookTitle.getTitle() + " registered.");
}
}
}
class Book {
private String title;
public Book(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
// Called by Library's printAllBooks method (library.toString())
@Override
public String toString() {
return "Book{" +
"title='" + title + '\'' +
'}';
}
// auto generated by IDE (important for checking whether a collection contains an equal object)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Book)) return false;
Book book = (Book) o;
return title.equals(book.title);
}
// auto generated by IDE (important for checking whether a collection contains an equal object)
@Override
public int hashCode() {
return Objects.hash(title);
}
}
class Library {
List<Book> library = new ArrayList<Book>();
public boolean isBookInLibrary(Book book){
return library.contains(book);
}
public void add(Book book) {
library.add(book);
}
public void printAllBooks() {
System.out.println(library.toString());
}
}
Output:
Book Title 1 registered.
This book (Title 1) is not unique
Book Title 2 registered.
[Book{title='Title 1'}, Book{title='Title 2'}]
Process finished with exit code 0