How to return a value from a Map with a method?
如何在这种情况下返回int值?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.*; public class ShoppingCart { private Map<String, Purchase> shoppingCart = new HashMap<String, Purchase>(); public void add (String product, int price) { Purchase purchase = new Purchase(product, 1, price); shoppingCart.put(product, purchase); } public int totalPrice() { //How do I accomplish this? I want to return all the prices summed together } } } |
购买方法的构造函数是:
1 |
您需要迭代地图值总和总价
例如,此代码将起作用。
1 2 3 4 5 6 7 | public int totalPrice() { int sum = 0; for(Purchase p:shoppingCart.values()){ sum+=p.getPrice(); } return sum; } |
循环遍历Map(Javadoc)中的值。 由于这很可能是家庭作业,我会让你弄明白其余的。
在下面的代码中,您不需要再次运行循环...
import java.util。*;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class ShoppingCart { private int sum = 0; private Map<String, Purchase> shoppingCart = new HashMap<String, Purchase>(); public void add (String product, int price) { Purchase purchase = new Purchase(product, 1, price); if(!shoppingCart.contains(product)){ shoppingCart.put(product, purchase); sum += price; } } public int totalPrice() { return price; } } } |
1 2 3 4 5 |
1 2 3 4 5 6 7 | public int totalPrice() { int i = 0; for(Purchase purchase : shoppingCart.values()) { i += purchase.getPrice(); } return i; } |
通过地图迭代并总结每次购买的价格