【问题标题】:Calculating total price计算总价
【发布时间】:2016-09-07 16:39:16
【问题描述】:

我有一个抽象类Transaction,我想计算每个Transaction 的总价格。总价的计算方法是在Map 中获取每个Product 的价格,然后将该价格乘以每个Product 的数量。我只是不知道如何将这些价格乘以 Map 中的值。任何人都可以帮助我吗?我几乎尝试了所有方法,但没有任何效果。

public abstract class Transaction
{
    //Attributes
    ...

    //Links

    Map<Product,Integer> products;

    //Constructor

    Transaction()
    {
        id = newTrId.incrementAndGet();
        date = new Date();
        products = new HashMap<>();
    }

    abstract void addProduct(Product aProduct, int aQuantity);


    BigDecimal calculateTotal()
    {
        BigDecimal total = new BigDecimal(0);

        for(Product eachProduct : products.keySet())
        {
            total.add(eachProduct.getPrice());
        }
        for (Integer eachProduct : products.values())
        {

        }

        return total;
    }
}

【问题讨论】:

  • total.add(eachProduct.getPrice() * products.get(eachProduct)); 这将获取Integer 中的products Map 并乘以eachProduct 的价格。将其添加到您的 for-each 循环中,而不是执行另一个循环。

标签: java


【解决方案1】:

BigDecimal 是不可变的,add 不会更改调用它的对象。所以需要重新赋值add的结果:

BigDecimal calculateTotal() {
  BigDecimal total = new BigDecimal(0);
  for (Map.Entry<Product, Integer> entry : products.entrySet()) {
    total = total.add(BigDecimal.valueOf(entry.getKey().getPrice() * entry.getValue()));
  }
  return total;
}

【讨论】:

    【解决方案2】:

    你很亲密。这里看看:

    BigDecimal calculateTotal()
    {
        BigDecimal total = new BigDecimal(0);
    
        for(Product eachProduct : products.keySet())
        {
            total.add(eachProduct.getPrice() * products.get(eachProduct));
        }
    
        return total;
    }
    

    唯一的区别是这一行:total.add(eachProduct.getPrice() * products.get(eachProduct));

    我添加这个是为了从与Product 关联的地图中获取Integer。

    如果使用 Java 8,你也可以做一个流。

    total = new BigDecimal(map.keySet()
         .stream().mapToDouble( product -> product.getPrice() * products.get(product) )
         .sum());
    

    【讨论】:

    • 谢谢,但是 NetBeans 说我这样做时不能将 double 转换为 BigDecimal。
    • 嗯,当我测试它时它工作了。您使用的是 Java 8 吗?
    【解决方案3】:

    我只是不知道如何将这些价格乘以数量 作为Map 中的值。谁能帮帮我?

    这可以通过迭代Map 的条目 来完成,以便将数量(Map 的值)乘以其价格,如下所示:

    BigDecimal calculateTotal() {
        BigDecimal total = new BigDecimal(0);
        for (Map.Entry<Product, Integer> entry : products.entrySet()) {
            total = total.add(
                BigDecimal.valueOf(entry.getKey().getPrice()).multiply(
                    BigDecimal.valueOf(entry.getValue())
                )
            );
        }
        return total;
    }
    

    注意:我假设Product#getPrice() 返回double。

    NB 2由于BigDecimal是不可变的,您需要在每次迭代时重新分配变量total。

    NB 3为避免在计算中丢失任何精度,您需要将所有内容都转换为BigDecimal。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多