java - 使用迭代器在 HashMap 中搜索特定值

标签 java bluej

我正在尝试使用迭代器在 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)) {

您将StringStringsHashSet 进行比较。 这就像将苹果与梨进行比较一样;它永远是错误的。

因此,您要么想要一个 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/

相关文章:

java - 从高度调整图像大小

java - 在 Java 中捕获 Unresolved 编译错误

java - 从数据库中检索图像并显示在标签中

java - 需要帮助来理解这个 for 循环的作用及其工作原理

bluej - 你如何在 BlueJ 中设置字体?

java - 在 Java 中,有什么方法可以在给定显示名称的情况下获取区域设置?

java - 将 GET 方法 url 转换为逻辑永久链接

java - BlueJ - 我的程序编译没有错误但没有运行

java - 我的 Java Error 构造函数在类中无法应用于给定类型;

java - 使用 filewriter 将哈希集写入 txt