Question 111
A retail system models each item for sale as a Product and uses a Store object to hold every product currently tracked by the store. The two classes are shown below; only the method totalValueOfLowStock in Store is left for you to complete. Everything else is already written.
public class Product
{
private String name;
private double price;
private int quantity;
public Product(String theName, double thePrice, int theQuantity)
{
name = theName;
price = thePrice;
quantity = theQuantity;
}
public String getName() { return name; }
public double getPrice() { return price; }
public int getQuantity() { return quantity; }
}
public class Store
{
/** Inventory of products currently tracked by this store. Never null. */
private ArrayList<Product> inventory;
public Store(ArrayList<Product> startingInventory)
{
inventory = startingInventory;
}
/** Returns the total dollar value of all products in inventory whose current
* quantity is strictly less than threshold. The dollar value of a single
* product is its price multiplied by its quantity. If no product has a
* quantity below threshold, the method returns 0.0.
* @param threshold the cutoff quantity; assumed to be non-negative
* @return the sum of price * quantity over all low-stock products
*/
public double totalValueOfLowStock(int threshold) { /* to implement */ }
}
Write the method totalValueOfLowStock. The method must iterate over every product in inventory and accumulate the dollar value price * quantity for each product whose current quantity is strictly less than threshold.
Suppose inventory holds three products:
{name:"widget", price:4.50, quantity:2}, {name:"gizmo", price:10.00, quantity:7}, {name:"bolt", price:0.25, quantity:3}.
A call to totalValueOfLowStock(5) selects the "widget" (quantity 2) and the "bolt" (quantity 3) because 7 is not less than 5. The returned value is \(4.50 \times 2 + 0.25 \times 3 = 9.75\).
public double totalValueOfLowStock(int threshold)Main Solution
Sample Solution
public double totalValueOfLowStock(int threshold)
{
double total = 0.0;
for (int i = 0; i < inventory.size(); i++)
{
Product p = inventory.get(i);
if (p.getQuantity() < threshold)
{
total = total + p.getPrice() * p.getQuantity();
}
}
return total;
}
Scoring notes. Points are earned for: iterating over every index of inventory (a for or enhanced-for loop both work); retrieving each Product via get(i) and using its accessor methods rather than touching the private fields; comparing getQuantity() strictly to threshold; accumulating getPrice() * getQuantity() only for low-stock products; and returning the correct double total. Common errors include using a non-strict comparison (which includes products whose quantity equals threshold) or accessing inventory.get(i).price directly.
Answer images

