ShoppingListItem.java
package problem2class;
public class ShoppingListItem {
private String name;
private int numOfItems;
private double price;
public ShoppingListItem(String name, int quantity, double pricePerUnit) {
this.name = name;
numOfItems = quantity;
price = pricePerUnit;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumOfItems() {
return numOfItems;
}
public void setNumOfItems(int numOfItems) {
this.numOfItems = numOfItems;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public double getCost() {
return numOfItems * price;
}
public void setQuantity(int quantity) {
numOfItems = quantity;
}
public static void main(String[] linh) {
ShoppingListItem I1;
I1 = new ShoppingListItem("Kenturky",12,1200);
System.out.println("Now show the content of the Item:");
System.out.println("Name is:"+I1.getName() + " Price for each item:"+I1.getPrice() +" Num of items:"+I1.getNumOfItems());
System.out.println("So the cost is: "+I1.getCost());
}
}
ShoppingList.java
package problem2class;
public class ShoppingList {
public static ShoppingListItem[] items = new ShoppingListItem[10];
// public static int index=0;
public static double totalCost=0;
static ShoppingListItem I1 = new ShoppingListItem("milk",1,23);
// static ShoppingListItem I2 = new ShoppingListItem("cofee",12,30);
public ShoppingList() {
}
public void add(ShoppingListItem i) {
items[0] = new ShoppingListItem(i.getName(),i.getNumOfItems(),i.getCost());
//index++;
System.out.println("adding done!");
}
public double getTotalCost() {
//double totalCost =0;
int i;
int len = items.length;
System.out.println("length is"+len);
for (i = 0; i < items.length; i++) {
totalCost =totalCost + items[i].getCost();
System.out.println("each"+items[i].getCost());
}
return totalCost;
}
public static void main(String[] args) {
ShoppingList L1 = new ShoppingList();
L1.add(I1);
System.out.println("Total cost is" + L1.getTotalCost());
}
}
In the above exercise I add the items into the list then compute the totalCost of items stored in the list.
But it does not work properly.
Please help me solve this.
Thanks a lot!