2012-03-23 54 views
1

我有這個家庭工作任務的問題。我可以處理語法,但不處理邏輯。你能提供一些提示嗎?遞增值在一個地圖(JAVA)

我想要實現的是,add方法將通過使用increaseAmount方法增加產品的數量。現在,每次調用該方法時,它都會將金額的值重置爲「1」。使這變得複雜的是,我不允許使用任何其他的已經使用過的私有變量。

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

public void add (String product, int price) { 
     Purchase purchase = new Purchase (product, 1, price); 
        //the line abowe returns the value back to 1 which I don't want. 

     if(shoppingCart.containsKey(product)) { 

      shoppingCart.put(product, purchase); 
       purchase.increaseAmount(); 

     } 
     else { 
      shoppingCart.put(product, purchase); 

產品構造:

public Ostos(String product, int amount, int price) { 

代碼爲increaseAmount方法:

private int amount; 

public void increaseAmount() { 
    this.amount = (this.amount + 1); 
+2

順便說一句,歡迎堆棧溢出!如果您發現答案滿足您的問題,請將其標記爲已接受。你獎勵你的同齡人的努力,激勵人們在未來回答你,並通常提高質量:) – 2012-03-23 15:59:24

回答

6

在不創建一個新的採購開始時只是創建它,如果它不是已經存在

public void add (String product, int price) { 

     if(shoppingCart.containsKey(product)) { 
      Purchase purchase = shoppingCart.get(product); 
      purchase.increaseAmount(); 
      //You might have to put the purchase back into the cart I'm not sure 
     } 
     else { 
      Purchase purchase = new Purchase (product, 1, price); 
      shoppingCart.put(product, purchase); 
     } 
+0

這工作完美。謝謝! – Mark 2012-03-23 15:57:32

1

你必須檢索shoppingCart值,然後遞增量。您永遠不會撥打shoppingCart.get,因此您每次都會盲目地將新購買對象添加到地圖中,以取代該值。

+0

感謝您的幫助! – Mark 2012-03-23 15:58:10