2017-10-11 33 views
-2

我有一個關於HashMap的問題, 我有一類產品:如何從hashmap中獲得計數?

public class product{ 
    private String libele; 

和也是一類特殊的產品:

public class SpecialProd extends Product{ 
     private HashMap<Product, Price> comp = new HashMap<Product, Price>(); 
     public HashMap<Product, Price> getComp() { 
      return comp; 
     } 
} 

的問題是,我需要知道我有多麼的產品有有庫存,產品的總量和每個產品多少: 所以我用這個代碼在類存儲中:

public class Storage{ 

    private HashMap<Product, Price> port = new HashMap<Product, Price>(); 
public void total(){ 
     int nombre=0; 
     int total = 0; 
     int i=0; 
     for (Product p:port.keySet()){ 
      if (port.containsKey(a)){ 
       // ++nombre; 
      } 


     total = port.size(); 
     System.out.println(+nombre+ "of" +a.getLibele()); 
     } 

     System.out.println("total products:" +total); 


} 


    // this is an intern class 
    static class Part{ 
     private int price; 

     public Price(int price) { 
      this.price= price; 
     } 



     public int getprice() { 
      return price; 
     } 

     public void setPrice(int price) { 
      this.price= price; 
     } 


       } 




    } 

我無法獲得每件產品的計數和總價。

有什麼想法嗎?

+1

這可能是因爲您沒有做任何事情來獲取任何價格,或者首先將其填充。你只是得到你的散列表中的鍵的數量。除此之外,代碼不會運行,您從未定義的一些變量(例如:'a')。 –

+0

getPrice的方法不會做同樣的事情嗎? – Gate11

回答

0

您可以嘗試枚舉HashMap並獲取所需的值。

int count=0; 
for(p : port.keySet()){ 
count ++; 
price = price + port.get(a); 
} 
+0

我無法使用port.keyset(),因爲這些密鑰是產品。 – Gate11

+0

然後,也許你可以嘗試'while(port.containsKey()){// value evaluation}' – Neha

+0

public void prix(){ \t int count = 0; \t int Price = 0; (port.containsKey(Price)){ \t \t co ++; \t \t Price = Price + port.get(Price); \t} \t } 運營商+在storage.price – Gate11