有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

oop初学者java迭代arraylist方法删除和计数

我是学习迭代器的新手。我有一个叫做Book的类,我从中引用变量。我被要求使用迭代器和while循环,从集合中删除给定年份或更早年份出版的所有书籍。我正在研究的方法是最底层的。我不确定我的方法是否完全正确

public class Book
{
 private String title;
    private String author;
    private int yearPublished;
    private double bookPriceInCAD;

还有一家主要的书店

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");
    }
    }
    }  

我哪里做错了

  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;

共 (1) 个答案

  1. # 1 楼答案

    而不是创建新的整数值:

    int getYearPublished = aBook.getYearPublished(); if(getYearPublished <= aBook.getYearPublished()){

    使用您在方法签名中收到的参数(yearPublished):

    if(yearPublished <= aBook.getYearPublished()){

    这样,您的方法就变得依赖于插入其中的值,而不仅仅是aBook.getYearPublished()