import java.util.*;
public class Main
{
public static void main(String[] args)
throws Exception
{
final ArrayList<Book> books = new ArrayList<Book>();
Scanner scanner = null;
try
{
scanner = new Scanner(System.in);
while (true)
{
System.out.println("Name (empty will stop):");
if (scanner.hasNextLine() == false) { break; }
final String name = scanner.nextLine();
if (name == null || name.isEmpty()) { break; }
// Linear search by book.name
boolean found = false;
for(final Book book : books)
{
if (book != null)
{
if (name.equals(book.getName()))
{
found = true;
break;
}
}
}
if (found)
{
System.out.println("The book is already on the list. Let's not add the same book again");
continue;
}
else
{
System.out.println("Publication year:");
if (scanner.hasNextLine() == false) { break; }
final String year = scanner.nextLine();
if (year == null || year.isEmpty()) { break; }
final int publicationYear = Integer.parseInt(year.trim());
final Book book = new Book(name, publicationYear);
books.add(book);
}
}
}
finally
{
if (scanner != null) { scanner.close(); }
}
// NB! Don't alter the line below!
System.out.println("Thank you! Books added: " + books.size());
}
}
public class Book {
private String name;
private int publicationYear;
public Book(String name, int publicationYear) {
this.name = name;
this.publicationYear = publicationYear;
}
public String getName() {
return name;
}
public int getPublicationYear() {
return publicationYear;
}
public boolean equals(Object compared) {
// if the variables are located in the same position. they are equal
if (this == compared) {
return true;
}
// if the compared object is not of type Book, the objects are nt equal
if (!(compared instanceof Book)) {
return false;
}
// convert the object to a book Object
Book comparedBook = (Book) compared;
// if the values of the variables are equal, the objects are equal
if (this.name.equals(comparedBook.name)) {
return true;
}
return false;
}
}