带有用户输入字符串而不是hashmap名称的访问hashmap方法



我有两个hashmaps HashMap<String, String> verbHashMap<String, String> noun。我需要使用存储在String name中的用户输入访问其键和值。如何访问hashmaps,以便我不必在代码中明确说明哈希图的名称?

假设用户创建HashMap<String, String> adjective,该方法应处理hashmap在代码中未明确命名。我想到了尝试类似name.get(question)而不是noun.get(question)verb.get(question)之类的东西,但显然这是不可能的。我想使我的代码更加高效,以便用户可以访问不是"动词"或"名词"的hashmap。

我已经尝试查看给定的字符串方法,但没有什么真正适合的。我没有太多的运气找到解决这个问题的其他线程。

if(name.contains("verb")) {
    for(String question: verb.keySet()) {
        System.out.println(question);
        reader = new Scanner(System.in);
        hold = reader.nextLine();
        if(hold.equals(verb.get(question))) {
            System.out.println("CORRECT");
        } 
        else {
            System.out.println("INCORRECT");
        }
    }
} 
else if(name.contains("noun")) {
    for(String question : noun.keySet()) {
        System.out.println(question);
        hold = reader.nextLine();
        if(hold.equals(noun.get(question))) {
            System.out.println("CORRECT");
        } 
        else {
            System.out.println("INCORRECT");
        }
    }
}
else { System.out.println("not a set"); }
return "";

现在,一切都按预期的动词和名词打印。密钥打印,将String hold中存储的其他用户输入与与密钥关联的值进行比较,如果正确或不正确,则在转到Hashmap中的下一个密钥之前。

您的问题尚不清楚。用名词,动词和名称的类型更新问题。我假设根据我的理解,您有两个地图,其中有一些元素。

Map<String, String> verb;
Map<String, String> noun;

优化上述代码。创建下面的方法

private static void check(Map<String, String> map) {
   if(map != null){
       Scanner reader = new Scanner(System.in);
       map.forEach((key, value) -> {
          System.out.println(key);
          String hold = reader.nextLine();
          System.out.println(( hold.equals(value) ? "CORRECT" : "INCORRECT" ));
       });
   } else {
       System.out.println("not a set");
   }
}

并将此方法称为

this.check(name.contains("verb") ? verb:name.contains("noun") ? noun : null);

解释: 在调用check()方法时,我们是根据名称的值传递映射。地图可以是动词,名词或null。

如果您不知道条件操作员的工作方式,请在此处找到

最新更新