【发布时间】:2019-07-12 12:31:41
【问题描述】:
我有两个 HashMap HashMap<String, String> verb 和 HashMap<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 中的下一个键之前打印是否正确。
【问题讨论】:
-
请发帖Minimal, Complete, and Verifiable example。
name、verb等变量的类型和内容很难猜测。
标签: java eclipse hashmap user-input