Question

In: Computer Science

Java iteration method, I need a method which iterates through a collection of books and adjusts...

Java iteration method, I need a method which iterates through a collection of books and adjusts the price of all books published between the given parameters to give a 20% discount off the price of each book published between the given years?

Book class

public class Book
{

    private String title;
    private String author;
    private int yearPublished;
    private double bookPriceInCAD;


    public Book(String inputTitle, String inputAuthor, int inputYearPublished, double inputBookPriceInCAD){
     setTitle(inputTitle);
     setAuthor(inputAuthor);
     setYearPublished(inputYearPublished);
     setBookPriceInCAD(inputBookPriceInCAD);
    }

    public String getTitle(){
        return title;
    }

    public String getAuthor(){
        return author;
    }

    public int getYearPublished(){
        return yearPublished;
    }

    public double getBookPriceInCAD(){
        return bookPriceInCAD;
    }

    public void setTitle(String title){
        if(title !=null && !title.isEmpty()){
            this.title = title;
        } else if(title == null){
            throw new IllegalArgumentException("title cannot be null");
        } else if(title.isEmpty()){
            throw new IllegalArgumentException("title cannot be an empty String");
        }
     }

     public void setAuthor(String author){
        if(author !=null && !author.isEmpty()){
            this.author = author;
        } else if(author == null){
            throw new IllegalArgumentException("author cannot be null");
        } else if(author.isEmpty()){
            throw new IllegalArgumentException("author cannot be an empty String");
        }
    }

    public void setYearPublished(int yearPublished){
        if(yearPublished > 0){
            this.yearPublished = yearPublished;
        } else {
            throw new IllegalArgumentException("year published cannot be negative");
        }
      }

    public void setBookPriceInCAD(double bookPriceInCAD){
        if(bookPriceInCAD > 0){
            this.bookPriceInCAD = bookPriceInCAD;
        } else {
            throw new IllegalArgumentException("book price in CAD cannot be negative");
        }
    }

BookStore Class

import java.util.ArrayList;
import java.util.Iterator;
public class BookStore
{
  

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

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

    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 void displayBookDetails(){
        for(Book oneBook: bookList){
            oneBook.displayDetails();
          
      }
    }
  

    public static void main(String[] args){
        BookStore list = new BookStore();
        Book b1 = new Book("hello world","steven segal",2005,20.00);
        Book b2 = new Book("goodbye world","Jeff country", 208,10.00);
        Book b3 = new Book("no world","Bill Nye",202,30.00);
        list.addBook(b1);
        list.addBook(b2);
        list.addBook(b3);
        list.getBook(4);
        list.getBook(2);

        list.displayBookDetails();
    }
  
       public int donateBook(int yearPublished){
        Iterator<Book> iter = bookList.iterator();
        int count = 0;
        while(iter.hasNext()){
            Book aBook = iter.next();
          
            if(yearPublished <= aBook.getYearPublished()){
                iter.remove();
                count++;
            }
        }
        return count;
    }
    public void applyDiscountToBook(int beginYear, int endYear){
    }
   

Solutions

Expert Solution

Hi,

Please find the apply discount method:

Steps:

  • Iterate each book in the collection.
  • Get the Year of Publish.
  • Check if its in between start and end year.
  • Get the book price.
  • Apply the 20% discount.
  • Set the discounted price to the book object.


Java Method:

public void applyDiscountToBook(int beginYear, int endYear){
       Iterator<Book> iter = bookList.iterator();
       while(iter.hasNext()){
            Book aBook = iter.next();
        
            if(beginYear <= aBook.getYearPublished() && endYear >= aBook.getYearPublished()){
               double beforeDiscountPrice = aBook.getBookPriceInCAD(); //getBookPrice
               double afterDiscountPrice= beforeDiscountPrice * 0.8 ;//20% off
               aBook.setBookPriceInCAD(afterDiscountPrice);//set discounted price
            }
        }
    }


Screenshot:

Hope this helps.


Related Solutions

I need this in JAVA Lab9B In each method returned an integer. In this part of...
I need this in JAVA Lab9B In each method returned an integer. In this part of the lab, all methods will have a void return type and take in an array of integers as a parameter. You’re going to write a program that creates a mini database of numbers that allows the user to reset the database, print the database, add a number to the database, find the sum of the elements in the database, or quit. In main, you...
In Java I need a Flowchart and Code. Write the following method that tests whether the...
In Java I need a Flowchart and Code. Write the following method that tests whether the array has four consecutive numbers with the same value: public static boolean isConsecutiveFour(int[] values) Write a test program that prompts the user to enter a series of integers and displays it if the series contains four consecutive numbers with the same value. Your program should first prompt the user to enter the input size—i.e., the number of values in the series.
Java Searching and Sorting, please I need the Code and the Output. Write a method, remove,...
Java Searching and Sorting, please I need the Code and the Output. Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (After deleting an element, the number of elements in the array is reduced by 1.) Assume that...
Java programming. *******I Need complete the following requirements in this project: 1/ Remove the applyRandomBonus method...
Java programming. *******I Need complete the following requirements in this project: 1/ Remove the applyRandomBonus method from the test class 2/ Create a File, Printwriter for an output file yourlastnameErrorLog.txt 3/ Set your maximum array size for accounts to 10 4/ Catch InputMismatch and ArrayIndexOutOfBounds exceptions when reading data from the file: a. Skip any lines that cause an exception b. Write information about the exception to the log file, yourlastnameError.txt c. Include exception type and line number in exception...
I need a full java code. And I need it in GUI With the mathematics you...
I need a full java code. And I need it in GUI With the mathematics you have studied so far in your education you have worked with polynomials. Polynomials are used to describe curves of various types; people use them in the real world to graph curves. For example, roller coaster designers may use polynomials to describe the curves in their rides. Polynomials appear in many areas of mathematics and science. Write a program which finds an approximate solution to...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is...
JAVA JAVA JAVA Hey i need to find a java code for my homework, this is my first java homework so for you i don't think it will be hard for you. (basic stuff) the problem: Write a complete Java program The transport Company in which you are the engineer responsible of operations for the optimization of the autonomous transport of liquid bulk goods, got a design contract for an automated intelligent transport management system that are autonomous trucks which...
In JAVA Implement the moveMinToFront method in IntSinglyLinkedList. The moveMinToFront method looks through the list to...
In JAVA Implement the moveMinToFront method in IntSinglyLinkedList. The moveMinToFront method looks through the list to find the element with the minimum value. It moves that element to the front of the list. Before abstract view: [7, 3, 2] After Abstract view: [2,7,3] Before Abstract view: [4,1,7] After Abstract view: [1,4,7] public void moveMinToFront() { } Test: package net.datastructures; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Random; public class IntSinglyLinkedListTest { @Test public void moveMinToFrontTestEmpty() { IntSinglyLinkedList s...
JAVA JAVA JAVA . I need to convert a string input to int array, for example...
JAVA JAVA JAVA . I need to convert a string input to int array, for example if user enters 12 / 27 / 2020 , I want to store each value in a separate array and add them afterwards.
Just need java code for a small business that books shows and gives out a receipt...
Just need java code for a small business that books shows and gives out a receipt after placing order on what show they want
Which java collection have you used the most? and why? What does static mean in Java...
Which java collection have you used the most? and why? What does static mean in Java and when should you use it? (Both static variable and static method) What does abstract keyword mean in java and when should you use? (Both abstract class and method)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT