2016-09-07 2 views
2

나는 각각 Transaction의 총 가격을 계산하기 위해 추상적 인 클래스 Transaction을 가지고 있습니다. 총 가격은 각각 Product의 가격을 Map에 입력 한 다음 해당 가격에 각각 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; 
    } 
} 
+1

'total.add (eachProduct.getPrice() * products.get (eachProduct)) : 그래서 당신은 add의 결과를 재 할당 할 필요가 '각 제품의 가격으로 곱하면된다. 다른 루프를 수행하는 대신'for-each' 루프에 추가하십시오. – Orin

답변

0

난 그냥 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; 
} 

NB : I Product#getPrice()double을 반환한다고 가정합니다.

NB 2BigDecimal불변이다, 당신은 각 반복에서 당신의 변수 total을 다시 지정할 필요가 없다.

NB 3 계산의 정확도를 잃지 않으려면 모든 것을 BigDecimal으로 변환해야합니다.

0

가까운 사이. 여기 좀 봐 :

total.add(eachProduct.getPrice() * products.get(eachProduct)); 내가 Product와 관련된지도에서 Integer를 잡기 위해이 추가 :

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

    for(Product eachProduct : products.keySet()) 
    { 
     total.add(eachProduct.getPrice() * products.get(eachProduct)); 
    } 

    return total; 
} 

유일한 차이점은이 라인이다.

Java 8을 사용하는 경우 스트림을 처리 할 수도 있습니다.

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

감사합니다. NetBeans에서는이 작업을 수행 할 때 double을 BigDecimal로 변환 할 수 없다고 말합니다. – Joanna

+0

흠, 테스트했을 때 작동했습니다. Java 8을 사용하고 있습니까? – Orin

1

BigDecimal은 불변이며 add가 호출되는 객체를 변경하지 않습니다. `이것은`products`의`Integer`을 사로 잡고`지도,

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