我正在尝试使用迭代器在 HashMap 中搜索特定值,目前我有这个方法。我对 Java 很陌生,因此非常感谢您的帮助。 helper.readAMap 是存储响应的 HashMap ,响应是在用户输入某个单词时生成的。
public String generateResponse(String words)
{
HashMap<String, String> map = new HashMap();
map = helper.readAMap("replies.txt");
Iterator<String> it = map.keySet();
while(it.hasNext()) {
String word = it.next();
String response = map.get(word);
if(response != null) {
return response;
}
}
return pickDefaultResponse();
}
最佳答案
这里:
if(key.equals(words)) {
您将String
与Strings
的HashSet
进行比较。 这就像将苹果与梨进行比较一样;它永远是错误的。
因此,您要么想要一个 String
作为方法的参数,要么想要生成对所有单词的响应。
我希望你想这样做:
if(words.contains(key)) { // Your input contains the key
return map.get(key); // Retrieve the response to the key from the map
}
关于java - 使用迭代器在 HashMap 中搜索特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33918910/