This commit is contained in:
louiscklaw
2025-02-01 01:58:47 +08:00
parent b3da7aaef5
commit 04dbefcbaf
1259 changed files with 280657 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
public class Ex1 {
public static void main(String [] args) {
Invoice inv = new Invoice("A123", 4);
double total=0;
inv.addItem("U-231", 34.5, 10);
inv.addItem("J-994", 124.5, 5);
inv.addItem("K-674", 4.5, 100);
for (int i=0; i<inv.getItemCount(); i++) {
System.out.println(inv.getItem(i));
total += inv.getItem(i).getItemTotal();
}
System.out.println("Invoice Total = " + total);
}
}

View File

@@ -0,0 +1,42 @@
public class Invoice {
private String invNumber;
private Item [] itemList;
private int itemCount;
public Invoice(String invNumber, int itemNum) {
// 1. Set instance variable invNumber
// 2. Create an array of Item with number of elements specified
// by parameter itemNum. Refer to Topic 4.6, Slide 9
// 3. Set itemCount to 0, as there is no Item initially.
this.invNumber = invNumber;
itemList = new Item[itemNum];
itemCount = 0;
}
public String getInvNumber() {
return invNumber;
}
public Item[] getItemList() {
return itemList;
}
public int getItemCount() {
return itemCount;
}
public Item getItem(int index) {
return itemList[index];
}
public void addItem(String productCode, double price, int quantity) {
if (itemCount < itemList.length) {
// create a new Item; Refer to Topic 4.6, Slide 9
// save item to appropriate element in itemList
itemList[itemCount] = new Item(productCode, price, quantity);
itemCount++;
} else {
System.out.println("Failed to add new item; max already");
}
}
}

View File

@@ -0,0 +1,19 @@
public class Item {
private String productCode;
private double price;
private int quantity;
public Item(String productCode, double price, int quantity) {
this.productCode = productCode;
this.price = price;
this.quantity = quantity;
}
public double getItemTotal() {
return price * quantity;
}
public String toString() {
return productCode +":" + price + "*" + quantity + "=" + getItemTotal();
}
}