【发布时间】:2015-09-18 09:26:36
【问题描述】:
这是我的课堂作业。我一直在输出中得到错误的杂货。运行代码时我应该如何获取正确的项目?
这是我目前得到的输出:
购物者姓名:Gary
冰淇淋:5 件,每件 4.25 美元 = 21.25 美元
冰淇淋:5 件,每件 4.25 美元 = 21.25 美元
----> 小计 = $42.5
----> 7% 税 = 2.975 美元
---->总计 = $45.475
购物者姓名:Sally
冰淇淋: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()方法?