【发布时间】:2013-08-01 10:57:16
【问题描述】:
我一直在尝试让我的小型应用程序仅打印哈希图中的特定键(其中不包含“不需要的”字符串)。我尝试这样做的方式如下所示:
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
但是,它的目的是打印它(因为它应该省略其中包含“hi”和“oat”的键,它们应该离开:)
black shoes = 1
我不知道为什么我看不到错误,但希望有人可以帮助我指出。
【问题讨论】:
-
在打印出来之前,您必须检查是否可以在每个键中找到任何不需要的字符串...在您的解决方案中,您的 for 循环仅检查您的两个不需要的字符串之一是否在键中.例如。 if (!blackshores.contains("hi")) sysout(...) 这就是你得到错误结果的原因