67 lines
1.5 KiB
Java
67 lines
1.5 KiB
Java
|
|
/**
|
|
* An item that can be stored in a ShoppingCart
|
|
*
|
|
* @author 5w7-mf4-u1
|
|
*
|
|
*/
|
|
|
|
public class CartItem {
|
|
|
|
private double price;
|
|
private String item;
|
|
private int quant;
|
|
|
|
/**
|
|
*
|
|
* Initializes a CartItem with the following variables
|
|
*
|
|
* @param name Name of the item
|
|
* @param quantity Quantity of the item
|
|
* @param pricePerUnit Price per unit of the item
|
|
* @throws IllegalArgumentException if the quantity is < 1
|
|
*/
|
|
public CartItem(String name, int quantity, double pricePerUnit) throws IllegalArgumentException {
|
|
if (quantity > 0) {
|
|
price = pricePerUnit;
|
|
item = name;
|
|
quant = quantity;
|
|
} else {
|
|
throw new IllegalArgumentException();
|
|
}
|
|
|
|
}
|
|
|
|
/**
|
|
* Returns the total price of a CartItem
|
|
*
|
|
* @return The total price of the CartItem
|
|
*/
|
|
public double getCost() {
|
|
return price * quant;
|
|
}
|
|
|
|
/**
|
|
* Sets the Quantity of a CartItem to:
|
|
*
|
|
* @param quantity
|
|
* @throws IllegalArgumentException
|
|
*/
|
|
public void setQuantity(int quantity) throws IllegalArgumentException {
|
|
if (quantity < 1) {
|
|
throw new IllegalArgumentException();
|
|
}
|
|
quant = quantity;
|
|
}
|
|
|
|
/**
|
|
* Returns all CartItems in a Recipt and calcualtes the total
|
|
*/
|
|
|
|
@Override
|
|
public String toString() {
|
|
return String.format("%3d x %-30s %10.2f %10.2f\n", quant, item, price, price * quant);
|
|
}
|
|
|
|
}
|