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

CIS 355A - WEEK 2: PROGRAMMING PRACTICE Create an Invoice class that might serve

ID: 3855497 • Letter: C

Question

CIS 355A - WEEK 2: PROGRAMMING PRACTICE Create an Invoice class that might serve as a receipt for items sold. An Invoice should be defined by the following attributes: productName : String quantityPurchased : int pricePerItem : double Provide getters and setters for each attribute, making sure that the numeric values given are not negative. Set them to 0 if they are. Include a method that calculates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount as a double value. Write a test program that shows everything working.

Explanation / Answer

Invoice.java

====

public class Invoice {
private String productName;
private int quantityPurchased;
private double pricePerItem;

// CONSTRUCTOR
/**
* Invoice constructor.
* @param {String} pName Name of the product.
* @param {int} quantity Quantity of product.
* @param {double} price Price of product.
*/
public Invoice(String pName, int quantity, double price) {
this.productName = pName;
this.quantityPurchased = quantity;
this.pricePerItem = price;
}
  
// SETTERS
public void setProductName(String val) {
this.productName = val;
}
public void setQuantityPurchased(int val) {
// Set to zero in case negative
if (val < 0) val = 0;
this.quantityPurchased = val;
}
public void setPricePerItem(double val) {
// Set to zero in case negative
if (val < 0) val = 0;
this.pricePerItem = val;
}
  
// GETTERS
public String getProductName() {
return this.productName;
}
public int getQuantityPurchased() {
return this.quantityPurchased;
}
public double getPricePerItem() {
return this.pricePerItem;
}
  
// METHODS
/**
* Calculates the total amount.
*/
public double calcAmount() {
return this.pricePerItem * this.quantityPurchased;
}
};

InvoiceDriver.java

====

public class InvoiceDriver {
public static void main( String[] args ) {
int numItems;
double price;
  
// Test 1
numItems = 6;
price = 2.68;
// Looove pineapple juice!
Invoice i1 = new Invoice("Pineapple Juice", numItems, price);
// Asserts method's result with our calculations.
assert i1.calcAmount() == numItems*price;
System.out.print(".");
  
// Test 2
numItems = 5;
price = 3.98;
Invoice i2 = new Invoice("Chocolates Syrup", numItems, price);
// Asserts method's result with our calculations.
assert i2.calcAmount() == numItems*price;
System.out.print(".");
  
System.out.println();

}
}