在这种情况下如何返回int值?
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
}
}
}
购买方法的构造函数为:
public Purchase(String product, int amount, int price) {
最佳答案
您需要遍历地图值总和
例如,此代码将起作用。
public int totalPrice() {
int sum = 0;
for(Purchase p:shoppingCart.values()){
sum+=p.getPrice();
}
return sum;
}
关于java - 如何使用方法从Map返回值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9838695/