這是用於我的課堂作業。我一直在輸出中收到錯誤的groceryitem。代碼運行時我應該如何獲得正確的項目?當我將商品添加到購物車時出現錯誤的雜貨商品
這裏是輸出目前我得到:
購物名稱:加里
冰淇淋:5個單位在$ 4.25每單位= $ 21.25
冰淇淋:5個單位在$ 4.25 per unit = $ 21.25
---->小計= $ 42.5
- ---> 7%的稅= $ 2.975
---->共= $ 45.475
購物者名稱:薩利
冰淇淋:2個單位在每單位$ 4.25 = $ 8.5
冰淇淋:2個單位在每單位$ 4.25 = $ 8.5
---->小計= $ 17.0
----> 7%的稅= $ 1.1900000000000002
---->總= $ 18.19
車類:
public class Cart
{
public String Name;
public int ItemNum;
public double tax;
public Cart(String ShopperName){
Name = ShopperName;
}
public String getShopperName(){
return Name;
}
public int getItemNumber(){
return ItemNum;
}
public void addItem1(GroceryItem GroceryItem, int NumberItem){
GroceryItem = GroceryItem;
ItemNum = NumberItem;
}
public void addItem2(GroceryItem GroceryItem, int NumberItem){
GroceryItem = GroceryItem;
ItemNum = NumberItem;
}
public double getItemTotal(){
double item_total = (double) (GroceryItem.getCost()*getItemNumber());
return item_total;
}
public double getSubtotal(){
double subtotal = (double) (getItemTotal() + getItemTotal());
return subtotal;
}
public double getTaxTotal(){
double tax = .07;
double taxtotal = (double) (getSubtotal()*tax);
return taxtotal;
}
public double getTotal(){
double Total = (double) (getTaxTotal()+getSubtotal());
return Total;
}
public void printReceipt(){
System.out.println("Shopper Name: " + getShopperName());
System.out.println("----------------------");
System.out.println(GroceryItem.getName()+":"+ getItemNumber()+ " units at $" + GroceryItem.getCost()+" per unit"+ " = $"+ getItemTotal());
System.out.println(GroceryItem.getName()+":"+ getItemNumber()+ " units at $" + GroceryItem.getCost()+" per unit"+ " = $"+ getItemTotal());
System.out.println("----> Subtotal = $" + getSubtotal());
System.out.println("----> 7% tax = $" + getTaxTotal());
System.out.println("---->Total = $" + getTotal());
System.out.println("");
System.out.println("");
System.out.println("");
}
}
驅動程序類:
/**
* Driver for Cart and GroceryItem.
*/
public class Driver
{
public static void main(String[] args)
{
// create grocery items
GroceryItem item1 = new GroceryItem("milk", 3.39);
GroceryItem item2 = new GroceryItem("eggs", 1.75);
GroceryItem item3 = new GroceryItem("ice cream", 4.25);
// create new carts
Cart shopper1 = new Cart("Gary");
Cart shopper2 = new Cart("Sally");
// add items to first cart
shopper1.addItem1(item2, 1); //1 "eggs" is being added
shopper1.addItem2(item1, 5); //5 "milk" are being added
// add items to second cart
shopper2.addItem1(item3, 2); //2 "ice cream" are being added
shopper2.addItem2(item2, 2); //2 "eggs" are being added
// print cart's receipt
shopper1.printReceipt();
shopper2.printReceipt();
}
}
'GroceryItem = GroceryItem;'缺少GroceryItem字段的定義。但似乎你一直在覆蓋它。 –
另外,想想你想在這上面編程多久。我想購買934件物品。所以你想實現934 addItemXXX()方法? –