Click here to Skip to main content
15,847,903 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In this project i have four classes, but im not sure how my book and journal end up being added to the publicationList. How do i add them into the list. Here are my four classes.

What I have tried:

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();
    }            
}
Posted
Updated 8-Mar-23 7:01am
Comments
Richard MacCutchan 8-Mar-23 10:26am    
I would guess that a call to Database::addPublication would be the way.
Richard MacCutchan 8-Mar-23 11:35am    
Where is the main class that drives the actual program?
Freddie Francis 8-Mar-23 11:38am    
it is done on blueJ
Richard MacCutchan 8-Mar-23 12:07pm    
Which is fine if you understand Java. But looking at your response to OriginalGriff you have a big gap in your knowledge. I can highly recommend Java Tutorials Learning Paths[^].

Normally, I wouldn't post a "second solution", but this is a different problem:
Quote:
ive tried doing this but i am getting error message, undeclared variables.
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);
        }
    }
book and journal aren't a part of the Database class, and that's why you get the error message - it's telling you just that: "I can't find anything called "book"

And that's a good thing - because if it could find them, your app would crash pretty much immediately as you have made your addPublication method recursive, and worse unbounded recursive (which means it calls itself without end until it crashes).

Move the two calls out of that method and into the class where you create the Book and Journal class instances. (Which we can't see!)

You should expect to get syntax errors every day, probably many times a day while you are coding - we all do regardless of how much experience we have! Sometimes, we misspell a variable, or a keyword; sometimes we forget to close a string or a code block. Sometimes the cat walks over your keyboard and types something really weird. Sometimes we just forget how many parameters a method call needs.

We all make mistakes.

And because we all do it, we all have to fix syntax errors - and it's a lot quicker to learn how and fix them yourself than to wait for someone else to fix them for you! So invest a little time in learning how to read error messages, and how to interpret your code as written in the light of what the compiler is telling you is wrong - it really is trying to be helpful!

So read this: How to Write Code to Solve a Problem, A Beginner's Guide Part 2: Syntax Errors[^] - it should help you next time you get a compilation error!
 
Share this answer
 
Comments
Freddie Francis 8-Mar-23 12:18pm    
ive moved the calls into their respected class but it still tells me undeclared, for example here;

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;
database.addPublication(journal);
}
OriginalGriff 8-Mar-23 12:26pm    
You haven't created an instance of the Journal class, or created a variable in which to store it!
You need to go back a few steps, and re-read your course notes about "instances", "objects", and "classes".

A Car is a class of vehicle, "my car" is a variable holding an instance of a vehicle and "the Mercedes B Class I am driving" is the actual instance of the Car class in the variable.
Because both the Book and Journal classes inherit from the Publication class, they can be used anywhere the Publication class can - that is what inheriting is all about: a class that extends another class contains all the properties, methods, and fields that the base class does.

So since you have a collection that holds instances of the base class, it will also hold instances of any class that derives from that base class - in the same way that every class is ultimately derived from the Object class so a collection of Object values can hold any type of data.

Just call Database.addPublication, and pass it an instance of a Book or Journal
 
Share this answer
 
Comments
Freddie Francis 8-Mar-23 11:23am    
ive tried doing this but i am getting error message, undeclared variables.
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);
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900