gpt4 book ai didi

java - HashMap 键将不起作用

转载 作者:行者123 更新时间:2023-12-01 14:48:57 24 4
gpt4 key购买 nike

我有一个 HashMap,其中某些键(例如“crash”和“crashes”)返回相同的响应。我想创建一个新的 HashMap,将同义词映射到 responseMap 中的唯一键(例如,将 synonymMap 中的“crash”、“crashes”和“crashed”映射到“crash”)。

 private void fillSynonymMap()
{
synonymMap.put("crash", "crash");
synonymMap.put("crashes", "crash");
synonymMap.put("crashed", "crash");
}

我所困惑的是如何输入这些键,以便我可以简化下面的代码。

 private void fillResponseMap()
{
responseMap.put("crash",
"Well, it never crashes on our system. It must have something\n" +
"to do with your system. Tell me more about your configuration.");
responseMap.put("crashes",
"Well, it never crashes on our system. It must have something\n" +
"to do with your system. Tell me more about your configuration.");\
responseMap.put("crashed",
"Well, it never crashes on our system. It must have something\n" +
"to do with your system. Tell me more about your configuration.");
}



public String generateResponse(HashSet<String> words)
{
for (String word : words) {
String response = responseMap.get(word);
if(response != null) {
return response;
}
}

// If we get here, none of the words from the input line was recognized.
// In this case we pick one of our default responses (what we say when
// we cannot think of anything else to say...)
return pickDefaultResponse();
}

最佳答案

经过一番困惑之后,我编写了一个函数,该函数将在返回默认消息之前查找同义词。

public String getResponse()
{
HashMap<String, String> responseMap = new HashMap<String, String>();
HashMap<String, String> synonymMap = new HashMap<String, String>();

responseMap.put("crash", "Hello there");
// Load the response value.
synonymMap.put("crash", "crash");
synonymMap.put("crashed", "crash");
synonymMap.put("crashes", "crash");
// Load the synonyms.

String input = "crashed";
// Select input value.

if(responseMap.containsKey(input))
{
// Response is already mapped to the word.
return responseMap.get(input);
}
else
{
// Look for a synonym of the word.
String synonym = synonymMap.get(input);
if(!synonym.equals(input) && responseMap.containsKey(synonym))
{
// If a new value has been found that is a key..
return responseMap.get(synonym);
}
}
// If no response, set default response.
input = "This is a default response";
return input;
}

正如您所看到的,该函数首先检查 key 是否存在。如果没有,它会尝试使用同义词。如果该同义词未通过测试,它将移至底部的默认代码,该代码会将输入设置为某个默认值并返回该值:)

关于java - HashMap 键将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15083860/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com