【发布时间】:2018-12-05 22:35:35
【问题描述】:
我有一个类,它采用由它们的名称、价格和数量确定的项目数组列表,并且应该打印每个唯一项目并在将多个相同项目添加到数组列表时相应地增加数量。
我当前的代码有 2 个问题:首先,它只打印数组列表中的最后一项。其次,它返回的打印项目数量不正确。
package shop;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class ShoppingCart {
static ArrayList<Product> cart;
public ShoppingCart() {
ShoppingCart.cart = new ArrayList<Product>();
}
@Override
public String toString() {
DecimalFormat format = new DecimalFormat ("#.00");
int quantity = 0;
double price = 0;
String name = null;
double total = 0;
for (Product p: cart) {
quantity = p.getQuantity();
price = p.getPrice();
name = p.getName();
total = p.getTotalPrice();
}
return quantity + " * GBP " + format.format(price) + " " + name + " = GBP " + format.format(total);
}
public void add(Product p) {
if(cart.size() > 0) {
for (int i = 0; i < cart.size(); i++) {
if(cart.get(i).getName().equals(p.getName())
&& cart.get(i).getPrice() == p.getPrice()) {
cart.get(i).setQuantity(cart.get(i).getQuantity() + p.getQuantity());
}else {
cart.add(p);
}
}
}else {
cart.add(p);
}
}
public static void main(String[] args) {
ShoppingCart newCart = new ShoppingCart();
Product apple, apples, milk, caulk, ice, snakes;
apple = new Product("Apples (4 pack)", 1.20, 1);
apples = new Product("Apples (4 pack)", 1.20, 2);
milk = new Product("Milk (1l)", 0.75, 1);
caulk = new Product("Caulk (1l)", 6.84, 1);
ice = new Product("Ice (1kg)", 4.30, 1);
snakes = new Product("Snake (5m)", 32.0, 1);
newCart.add(apple);
newCart.add(apple);
newCart.add(apple);
newCart.add(apple);
newCart.add(caulk);
newCart.add(milk);
System.out.println(newCart);
}
}
输出是
4 * GBP .75 Milk (1l) = GBP 3.00
我猜我的 toString() 和 add() 方法出了点问题,但我不知道是什么。
【问题讨论】:
-
我不知道你的输出应该是什么格式,我只是试图找到你的问题并告诉你如何解决它。请把它做得更好,以满足您的需求
-
总而言之——你应该(几乎总是)declare 使用接口 List,比如
List<Product> cart;,然后在 create 时选择实现实际列表ShoppingCart.cart = new ArrayList<>();(并使用“钻石”运算符<>- 您不必重复类型“产品”)