I am new to learning iterators. I have a class called Book which i am referencing variables from. I'm asked to use an iterator and while loop that removes all books published in the given year or earlier from the collection. The method I am working on is at the very bottom. I am not sure if my method is completely right
public class Book
{
private String title;
private String author;
private int yearPublished;
private double bookPriceInCAD;
and a main class Bookstore
import java.util.ArrayList;
import java.util.Iterator;
public class BookStore
{
// instance variables
private ArrayList<Book> bookList;
private String businessName;
public BookStore()
{
// initialise instance variables
bookList = new ArrayList<Book>();
businessName = "Book Store";
}
public BookStore(String inputBusinessName){
setBusinessName(inputBusinessName);
bookList = new ArrayList<Book>();
}
public void setBusinessName(String businessName){
if(businessName !=null && !businessName.isEmpty()){
this.businessName = businessName;
} else if(businessName == null){
throw new IllegalArgumentException("business Name cannot be null");
} else if(businessName.isEmpty()){
throw new IllegalArgumentException("business Name cannot be an empty String");
}
}
public String getBusinessName(){
return businessName;
}
/**
* to return bookList
*/
public ArrayList<Book> getBookList(){
return bookList;
}
public void addBook(Book book){
if(book!=null){
bookList.add(book);
}
}
public void getBook(int index) {
if((index >= 0) && (index <= bookList.size())) {
Book oneBook = bookList.get(index);
oneBook.displayDetails();
}
else{
System.out.println("Invalid index position");
}
}
/**
* to search if book exists
*/
public void searchBook(String title){
for(Book b: bookList){
String bookTitle = b.getTitle();
if(bookTitle.equalsIgnoreCase(title)){
b.displayDetails();
} else{
System.out.println("book not found");
}
}
}
Where am i going wrong here?
public int bookPublished(int yearPublished){
Iterator<Book> iter = bookList.iterator();
int count = 0;
while(iter.hasNext()){
Book aBook = iter.next();
int getYearPublished = aBook.getYearPublished();
if(getYearPublished <= aBook.getYearPublished()){
iter.remove();
count++;
}
}
return count;
Instead of creating a new integer value:
int getYearPublished = aBook.getYearPublished();
if(getYearPublished <= aBook.getYearPublished()){
Use the parameter you've received in the method's signature (yearPublished
):
if(yearPublished <= aBook.getYearPublished()){
By that, your method becomes dependant of the value inserted into it, and not only by aBook.getYearPublished()
.