2012-04-10 46 views
-2

我在寫一個方法來計算大學項目的一些訂單總數時遇到了困難。 Eclipse說,有一個錯誤,只詳細說明+是一個無效的AssignmentOperator。向對方添加雙打

一些細節:

  • 有沒有隱私問題。
  • 數量是一個int。
  • getPrice()返回一個double。
  • 是雙

這也可能是很簡單的東西,但正因爲如此,一個答案摸索是相當困難的。


public double calculateTotal(){ 
    for(OrderItem currentItem:items){ 
     for(int i=0;i<currentItem.quantity;i++){ 
      total+currentItem.product.getPrice(); 
     } 
    } 
    return total; 
} 

回答

7

我想你需要+=

public double calculateTotal(){ 
    for(OrderItem currentItem:items){ 
     for(int i=0;i<currentItem.quantity;i++){ 
      total += currentItem.product.getPrice(); 
     } 
    } 
    return total; 
} 

在你的榜樣,你只是把兩個數字加在一起,無所事事,結果。您需要將結果分配給一個變量。使用+=是簡寫total = total + currentItem.product.GetPrice();

您可能還需要初始化total變量;但也許是你班上的其他地方。

+0

+1是最快的:) – 2012-04-10 12:12:01

+0

好了,這樣的作品,非常感謝! – gideonparanoid 2012-04-10 12:13:25

+0

是的,我已經在構造函數中初始化變量,歡呼。 – gideonparanoid 2012-04-10 12:47:57

1

你不能只是添加兩個值,而不對結果做任何事情。我懷疑你的意思

 total += currentItem.product.getPrice(); 
1

代替+使用+=

total += currentItem.product.getPrice();