Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a class named GroceryList that represents a list of items to buy from the

ID: 3625073 • Letter: W

Question

Write a class named GroceryList that represents a list of items to buy from the market , and another class named GroceryItemOrder that represents a request to purchase a particular item in a given quantity (example : four boxes of cookies ). The GroceryList class should use an array field to store the grocery items and keep track of its size ( number of items in the list so far ) . Assume that a grocery list will have no more than 10 items . A GroceryList object should have the following methods :
public GroceryList()
public void add ( GroceryItemOrder item)
public double getTotalCost()
public GroceryItemOrder( String name , int quantity , double pricePerUnit)
public double getCost ()
public void setQuantity ( int quantity )

Explanation / Answer

GroceryList.java:

public class GroceryList {

    private GroceryItemOrder [] items;
    int itemCount;
   
    public GroceryList() {
        itemCount = 0;
        items = new GroceryItemOrder[10];
    }
    public void add ( GroceryItemOrder item) {
        items[itemCount] = item;
        itemCount++;
    }
    public double getTotalCost() {
        double totalCost = 0;
        for (int i=0; i<itemCount; i++) {
            totalCost += items[i].getCost();
        }
        return totalCost;
    }
   
    public static void main(String[] args) {
        // Some test code
        GroceryList gl = new GroceryList();
        gl.add(new GroceryItemOrder("cookies",4,.5));
        gl.add(new GroceryItemOrder("crackers",6,1));
        System.out.println("Total cost of groceries: "+gl.getTotalCost());
    }
}

---------------------------------------------------

GroceryItemOrder.java:

public class GroceryItemOrder {
    double quantity;
    String name;
    double pricePerUnit;
    public GroceryItemOrder( String name , int quantity , double pricePerUnit) {
        this.pricePerUnit = pricePerUnit;
        this.name = name;
        this.quantity = quantity;
    }
    public double getCost () {
        return pricePerUnit*quantity;
    }
    public void setQuantity ( int quantity ) {
        this.quantity = quantity;
    }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote