2013-08-01 39 views
1

我一直在试图让我的小应用程序只打印散列表中的特定键(其中不包含'不想要的'字符串)。在我试图这样做的方法如下所示:仅打印散列图中的特定键

Map<String, Integer> items = new HashMap<String, Integer>(); 

    String[] unwanted = {"hi", "oat"}; 

    items.put("black shoes", 1); 
    items.put("light coat", 10); 
    items.put("white shoes", 40); 
    items.put("dark coat", 90); 

    for(int i = 0; i < unwanted.length; i++) { 
     for(Entry<String,Integer> entry : items.entrySet()) { 
      if(!entry.getKey().contains(unwanted[i])) { 
       System.out.println(entry.getKey() + " = " + entry.getValue()); 
      } 
     } 
    } 

然而,它打印此:

dark coat = 90 
black shoes = 1 
light coat = 10 
white shoes = 40 
black shoes = 1 

但是,它的目的是打印此而不是(因为它应该与“省略键喜“和‘燕麦’内他们应该见好就收:)

black shoes = 1 

我不知道为什么我没有看到了问题,但希望有人可以帮我指出来。

+0

你必须检查是否有任何不必要的字符串可以在每个键中找到之前打印出来...在你的解决方案yoor for循环只检查你的两个不需要的字符串之一是否在键中。 例如如果(!黑shores.contains(“嗨”))sysout(...) 这就是为什么你有你的错误结果 – redc0w

回答

2

您的内部循环逻辑不正确。只要不需要的字符串不存在,它就会打印一个hashmap条目。

变化for循环逻辑如下图所示...

bool found = false; 
for(Entry<String,Integer> entry : items.entrySet()) { 
    found = false; 
    for(int i = 0; i < unwanted.length; i++) { 
     if(entry.getKey().contains(unwanted[i])) { 
      found = true;    
     } 
    } 
    if(found == false) 
     System.out.println(entry.getKey() + " = " + entry.getValue()); 
} 
1

如果你看到你的外循环:

for(int i = 0; i < unwanted.length; i++) 

然后遍历直通

String[] unwanted = {"hi", "oat"}; 

你的地图如下:

"dark coat" : 90 
"white shoes": 40 
"light coat" : 10 
"black shoes", 1 
在第一次迭代

因此,

unwanted[i]="hi" 

所以,你的内部循环不打印“白鞋子”和而它打印:

dark coat = 90 
black shoes = 1 
light coat = 10 

,因为它们不含有“喜”

在第二阶段,

unwanted[i]="oat" 

所以,你的内部循环不打印"dark coat""light coat"并打印从地图剩余:

white shoes = 40 
black shoes = 1 

因此你得到上述两个迭代的组合输出为:

dark coat = 90 
black shoes = 1 
light coat = 10 
white shoes = 40 
black shoes = 1 

所以你可以要做的就是尝试这个代码,其中内环路和外环路翻转:

Map<String, Integer> items = new HashMap<String, Integer>(); 

    String[] unwanted = {"hi", "oat"}; 
    items.put("black shoes", 1); 
    items.put("light coat", 10); 
    items.put("white shoes", 40); 
    items.put("dark coat", 90); 

    boolean flag; 
    for(Map.Entry<String,Integer> entry : items.entrySet()) { 
     if(!stringContainsItemFromList(entry.getKey(),unwanted)) 
      System.out.println(entry.getKey() + " = " + entry.getValue()); 
    } 

在上面的代码中,我们使用静态函数:

public static boolean stringContainsItemFromList(String inputString, String[] items) 
    { 
     for(int i =0; i < items.length; i++) 
     { 
      if(inputString.contains(items[i])) 
      { 
       return true; 
      } 
     } 
     return false; 
    } 

希望有帮助!