如何使用方法从Map返回值?

时间:2012-03-23 11:51:01

标签: java map

如何在这种情况下返回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) {

6 个答案:

答案 0 :(得分:2)

您需要迭代地图值和总价格

例如,此代码将起作用。

 public int totalPrice() {
      int sum = 0;
       for(Purchase p:shoppingCart.values()){
            sum+=p.getPrice();
       }
       return sum;
  } 

答案 1 :(得分:1)

循环浏览地图中的值(Javadoc)。由于这很可能是家庭作业,我会让你弄清楚其余部分。

答案 2 :(得分:0)

Iterate through map并将每次购买的价格相加

答案 3 :(得分:0)

public int totalPrice() {
    int i = 0;
    for(Purchase purchase : shoppingCart.values()) {
      i += purchase.getPrice();
    }
    return i;
}

答案 4 :(得分:0)

   Map<String, Purchase>  map = new HashMap<String, Purchase> ();

    for(String value : map.values()) {

    }

答案 5 :(得分:0)

在下面的代码中,您不需要再次运行循环...
 import java.util。*;

    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;
        }
    }  
}