Search code examples
javaooparraylistpolymorphismhierarchy

ArrayList of string and another arraylist


so i'm making a program to manage a book store, heres an example of whats supposed to do with the the following main:

        bookStore bookStore = new bookStore("Lelo");
        book l1 = new TecnicalBook("H. Schildt", "\"Java: The Complete Reference\"", 80, "Computer Science- Java");
        bookStore.addBook(l1);
        book l2= new AdventureBook("A. Christie", "\"The Man in the Brown Suit\"", 75, 14);
        bookStore.addBook(l2);
                
        
        Client c1 = new Premium("B. Antunes", "antunes@books.com");
        bookStore.addClient(c1);
        Client c2 = new Frequent("A. Oliveira", "oliveira@books.com");
        bookStore.addClient(c2);
        System.out.println("Initial stock:");
        bookStore.showBooks();
        bookStore.sale(l1, c1);
        System.out.println("Stock after selling:");
        bookStore.showBooks();
        System.out.println("Sales Volume:"+bookStore.SalesVolume);        
        bookStore.showClientsBooks(c1);

Should show this result:

Initial stock:
Author:H. Schildt   Title:"Java: The Complete Reference"   Base Price:80.0
Author:A. Christie   Title:"The Man in the Brown Suit"   Base Price:75.0
B. Antunes bought "Java: The Complete Reference", Tecnical Book of Computer Science- Java, for 72.0
Stock after selling:
Author:A. Christie   Title:"The Man in the Brown Suit"   Base Price:75.0
Sales Volume:72.0
B. Antunes bought: "UML Distilled". "The Man in the Brown Suit".

The only part that i cant do is the last line, showing the products that each client has bought, i was thinking of making an class that contained a string with the clients name and an arraylist of a book class, and then having an array list of that class for each client, but i'm not sure how to make this and theres probably a better way, Thanks

edit: i have this classes: class book class tecnicalbook extends book class adventurebook extends book

class client class regular extends client class frequent extends client class premium extends client

and i have the bookstore class where i have an array list of book and client objects.


Solution

  • You can add a list of Books to your Client class to keep track of sales:

    class Client {
    
        ...
    
        private List<Book> books;
    
        ClientBooks(Client client) {
            ...
    
            this.books = new ArrayList<>();
        }
    
        public void addBook(Book book) {
            this.books.add(book);
        }
    
        public void printBooks() {
            for (Book book : this.books) {
                System.out.println(book);
            }
        }
    }
    

    Selling a book can be implemented like this:

    List<Client> clients = ...
    
    String buyer = ...
    Book book = ...
    
    for(Client client : clients) {
        if (client.getName().equals(buyer)) {
            client.addBook(book);
        }
    }