【解決方法】書籍およびジャーナル オブジェクトを publicationlist 配列リストに追加する方法。

プログラミングQA


このプロジェクトには 4 つのクラスがありますが、私の本と雑誌がどのように publicationList に追加されるのかわかりません。 それらをリストに追加するにはどうすればよいですか。 これが私の4つのクラスです。

私が試したこと:

Java
<pre>public class Database {
    private ArrayList<Publication> publicationList;   // An array list collection of publications 

    /**
     * Create a new database
     */
    public Database() {
        publicationList = new ArrayList<Publication>();
    }

    /**
     * Add a publication
     *
     * @param publication The publication to be added
     */
    public void addPublication(Publication publication) {
        if (publicationList.contains(publication)) {
            System.out.println("This publication has already been added to the list: " + publication);
        } else {
            publicationList.add(publication);
        }
    }

    /**
     * Get the total number of publications
     *
     * @return The total number of publications
     */
    public int getTotal() {
        return publicationList.size();
    }

    public ArrayList<Book> getBooksByAuthor(String authorName) {
        ArrayList<Book> authorsBooks = new ArrayList<Book>();
        for (Publication publication : publicationList) {
            if (publication instanceof Book) { 
                Book book = (Book) publication; // cast the publication to a book
                if (book.getAuthor().equals(authorName)) { // check if the author's name matches
                    authorsBooks.add(book); // add the book to the list
                }
            }
        }
        return authorsBooks;
    }

    public int getNumberOfJournals(int month, int year) {
        int count = 0;
        for (Publication publication : publicationList) {
            if (publication instanceof Journal) {
                Journal journal = (Journal) publication;
                if (journal.getMonth() == month && journal.getYear() == year) {
                    count++;
                }
            }
        }
        return count;
    }

    public void printList() {
        ArrayList<Book> books = new ArrayList<>();
        ArrayList<Journal> journals = new ArrayList<>();

        // filter publications by type
        for (Publication publication : publicationList) {
            if (publication instanceof Book) {
                books.add((Book) publication);
            } else if (publication instanceof Journal) {
                journals.add((Journal) publication);
            }
        }

        // sort publications by category and then by title within each category
        Comparator<Publication> categoryComparator = new Comparator<Publication>() {
                @Override
                public int compare(Publication p1, Publication p2) {
                    if (p1 instanceof Book && p2 instanceof Journal) {
                        return -1; // book before journal
                    } else if (p1 instanceof Journal && p2 instanceof Book) {
                        return 1; // journal after book
                    } else {
                        // same category, compare by title
                        return p1.getTitle().compareToIgnoreCase(p2.getTitle());
                    }
                }
            };

        Collections.sort(books, categoryComparator);
        Collections.sort(journals, categoryComparator);

        // print out the publications
        System.out.println("Books:");
        for (Publication publication : books) {
            System.out.println(publication);
        }

        System.out.println("Journals:");
        for (Publication publication : journals) {
            System.out.println(publication);
        }

        System.out.println("Total number of publications: " + getTotal());
    }
}

Java
public class Publication {
    private String title;       // The title of the book
    private int year;           // The year when the book was published

    

    /**
     * Parameterized constructor for objects of class Publication
     * 
     * @param title     The title of the publication
     */
    public Publication(String title, int year) {
        this.title = title;
        this.year = year;
    }

    /**
     * Get the title of the publication
     *  
     * @return  The title of the publication
     */
    public String getTitle() {
        return title;
    }

    /**
     * Get the year when the journal was published
     *  
     * @return  The year when the journal was published
     */
    public int getYear()
    {
        return year;
    }

    public String toString() {
        return title + ", " + year;
    }

}

Java
<pre>public class Journal extends Publication 
{   
    // The year and month when the journal was published
    private int month;

    /**
     * Create a journal. 
     * 
     * @param title     The title of the journal
     * @param month     The month when the journal was published
     * @param year      The year when the journal was published
     */
    public Journal(String title, int month, int year)
    {
        super(title, year);
        this.month = month;
    } 

    /**
     * Get the month when the journal was published
     *  
     * @return  The month when the journal was published
     */
    public int getMonth()
    {
        return month;
    }
    
    /**
     * Get the details of the journal
     *  
     * @return  The details of the journal, i.e. the title, year and month
     */
    public String toString()
    {
        return super.toString() + " (" + getMonthName(month) + ")";     
    }             
    
    /**
     * Check if the journal is the same as the given one.
     * 
     * @param obj The given object.
     * 
     * @return true  if the journal and the given one have the
     *               same title, year and month;
     *         false otherwise
     */
    public boolean equals(Object obj) {        
        if (this == obj) return true;
        if ( !(obj instanceof Journal) ) return false;
        
        var another = (Journal) obj;
        return this.getTitle().equals(another.getTitle()) &&
               this.month == another.month &&
               this.getYear() == another.getYear();
    }    
    
    /**
     * To get the name of a given month
     * 
     * @param month A given month
     * @return  The month's name
     */
    private String getMonthName(int month) {
        switch (month) {
            case 1: return "January";
            case 2: return "February";
            case 3: return "March";
            case 4: return "April";
            case 5: return "May";
            case 6: return "June";
            case 7: return "July";
            case 8: return "August";
            case 9: return "September";
            case 10: return "October";
            case 11: return "November";
            case 12: return "December";
            default: return "Unknown";
        }
    }    
}

Java
<pre>public class Book extends Publication
{    
    private String author;      // The author of the book

    /**
     * Create a book. 
     * 
     * @param title     The title of the book.
     * @param author    The author of the book.
     * @param year      The year when the book was published.
     */
    public Book(String title, String author, int year)
    {
        super(title, year);
        this.author = author;
    }

    /**
     * Get the author of the book
     *  
     * @return  The author of the book
     */
    public String getAuthor()
    {
        return author;
    }

    /**
     * Get the details of the book
     *  
     * @return  The details of the book, i.e. the title, year and author
     */
    public String toString ()
    {
        return super.toString() + ", by " + author;     
    }         

    /**
     * Check if the book is the same as the given one.
     * 
     * @param obj The given object.
     * 
     * @return true  if the book and the given object have
     *               the same title, author and year
     *         false otherwise
     */
    public boolean equals(Object obj) {        
        if (obj == this) return true;
        if ( !(obj instanceof Book) )  return false;

        var another = (Book) obj;        
        return this.getTitle().equals(another.getTitle()) && 
        this.author.equals(another.author) &&
        this.getYear() == another.getYear();
    }            
}

解決策 2

通常、「2 番目の解決策」は投稿しませんが、これは別の問題です。

引用:

これを試してみましたが、宣言されていない変数というエラーメッセージが表示されます。

Java
public class Database {
    private ArrayList<publication> publicationList;   // An array list collection of publications 

    /**
     * Create a new database
     */
    public Database() {
        publicationList = new ArrayList<publication>();
    }

    /**
     * Add a publication
     *
     * @param publication The publication to be added
     */
    public void addPublication(Publication publication) {
        if (publicationList.contains(publication)) {
            System.out.println("This publication has already been added to the list: " + publication);
        } else {
            publicationList.add(publication);
            database.addPublication(book);
            database.addPublication(journal);
        }
    }

bookjournal は Database クラスの一部ではないため、エラー メッセージが表示されます。「”book” という名前のものが見つかりません」というメッセージが表示されます。

これは良いことです。なぜなら、それらが見つかった場合、アプリはすぐにクラッシュするからです。 addPublication メソッドは再帰的であり、さらに悪いことに無制限の再帰的です (つまり、クラッシュするまで終わりなく自分自身を呼び出します)。

2 つの呼び出しをそのメソッドから、作成するクラスに移動します。 BookJournal クラスのインスタンス。 (私たちには見えません!)

コーディング中に毎日、おそらく 1 日に何度も構文エラーが発生することを予期する必要があります。経験の豊富さに関係なく、誰もがそうです。 変数やキーワードのスペルを間違えることがあります。 文字列やコード ブロックを閉じるのを忘れることがあります。 猫があなたのキーボードの上を歩いて、とても奇妙なことをタイプすることがあります。 メソッド呼び出しに必要なパラメーターの数を忘れてしまうことがあります。

我々はすべての間違いを犯します。

そして、私たちは皆そうしているので、構文エラーを修正する必要があります。他の人が修正してくれるのを待つよりも、方法を学んで自分で修正する方がはるかに迅速です! したがって、エラー メッセージの読み方と、コンパイラが間違っていると言っていることに照らして記述されたコードを解釈する方法を学ぶことに少し時間を費やしてください。

だからこれを読んでください: 問題を解決するコードの書き方、初心者向けガイド パート 2: 構文エラー[^] – 次回コンパイル エラーが発生したときに役立つはずです。

解決策 1

なぜなら、両方の BookJournal クラスはから継承します Publication それが継承のすべてです。別のクラスを拡張するクラスには、基本クラスが行うすべてのプロパティ、メソッド、およびフィールドが含まれます。

したがって、基本クラスのインスタンスを保持するコレクションがあるため、その基本クラスから派生したクラスのインスタンスも保持します。これは、すべてのクラスが最終的にから派生するのと同じ方法です。 Object クラスのコレクション Object 値は、あらゆるタイプのデータを保持できます。

電話するだけ Database.addPublicationのインスタンスを渡します。 Book また Journal

コメント

タイトルとURLをコピーしました