2017-10-11 34 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