【问题标题】:Access HashMap methods with user input String instead of HashMap name使用用户输入字符串而不是 HashMap 名称访问 HashMap 方法
【发布时间】:2019-07-12 12:31:41
【问题描述】:

我有两个 HashMap HashMap<String, String> verbHashMap<String, String> noun。我需要使用存储在String name 中的用户输入来访问他们的键和值。如何访问 HashMap,这样我就不必在代码中明确声明 HashMap 的名称?

假设用户创建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 中的下一个键之前打印是否正确。

【问题讨论】:

标签: java eclipse hashmap user-input


【解决方案1】:

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

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() 方法时,我们根据 name 的值传递 map。 map 可以是动词、名词或 NULL。

如果你不知道条件运算符是如何工作的,请找here

【讨论】:

    猜你喜欢
    • 2018-01-20
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 2019-04-27
    • 2020-08-09
    • 2019-02-07
    相关资源
    最近更新 更多