我必须在类ArrayList<FictionBook>中填充我的Librarian,但是当我使用fictionBooks.add();时,它无法识别变量fictionBooks。这是我当前的代码。另外我不确定如何用add(String, String)填充它。

public class FictionBook {
    private String author;
    private String title;
    private static final int AVAILABLE = 1;
    private static final int ONLOAN = 0;

    public FictionBook(String theAuthor, String theTitle){
        this.author = theAuthor;
        this.title = theTitle;
    }

    public int borrow() {
        System.out.println("The book is already borrowed.");
        return ONLOAN;
    }

    public int returnB() {
        System.out.println("The book was just returned.");
        return AVAILABLE;
    }

    public String getAuthor() {
        return author;
    }

    public String getTitle() {
        return title;
    }
}


我在这里创建arraylist:

import java.util.*;

public class Library {
    private static final int CAPACITY = 200;
    public ArrayList<FictionBook> fictionBooks = new ArrayList<FictionBook>();

    public Library() {
        //fictionBooks = new ArrayList<FictionBook>();
    }

    public void addBook(FictionBook book) {
        fictionBooks.add(book);
    }

    public void deleteBook(FictionBook book) {
        fictionBooks.remove(book);
    }

    public void borrowBook(FictionBook book) {
    }

    public void returnBook(FictionBook book) {
    }

    public void sort() {
        Collections.sort(fictionBooks, String.CASE_INSENSITIVE_ORDER);
    }
}


我需要在其中包含(“作者”,“标题”)的地方填充它:

public class Librarian {
    public static void main(String[] args) {
        fictionBooks.add("Jon", "Tiltle");
    }
}

最佳答案

您的fictionBooks ArrayList属于您的Library类。这意味着您首先需要创建Library的实例:

Library library = new Library();


然后,由于您的fictionBooks变量是FictionBook的列表,因此必须首先创建一个变量,然后才能将其添加到列表中,如下所示:

FictionBook fictionBook = new FictionBook("Jon", "Title");


现在,您可以访问新库的fictionBooks变量,并将新创建的fictionBook添加到其中:

library.fictionBooks.add(fictionBook);


但是,由于您在Library中已经有一个名为addBook(FictionBook)的方法,因此我建议像这样使用它:

library.addBook(fictionBook);


最后两个步骤可以压缩为一行,因此完成的代码如下所示:

public class Librarian {
    public static void main(String[] args){
        Library library = new Library();
        //Creating and adding the Fiction Book to the list in a single line of code.
        library.addBook(new FictionBook("Jon", "Title"));
    }
}


这里已经载有正确答案,但我只是想进一步阐述一下,以防它可能帮助您更好地理解问题。 :)

10-05 19:03