任务是询问一些随机卡片的定义。引入卡并访问此方法后,对应于密钥的值存在,并且仍返回null。
pair.get(a)始终显示为空
public static void ask() {
System.out.println("How many times to ask?");
int ask = scan.nextInt();
scan.nextLine();
Random random = new Random();
Object[] values = pair.keySet().toArray();
int retur = random.nextInt(values.length);
int i = 0;
for (String iterator : pair.keySet()) {
if (i <= ask) {
System.out.println("Print the definition of \"" + values[retur] + "\":");
String a = scan.nextLine();
System.out.println(a.equals(pair.get(values[retur])) ? "Correct answer." :
"Wrong answer. The correct one is \"" + pair.get(values[retur]) +
"\", you've just written the definition of \"" + pair.get(a) + "\".");
}else
break;
}
答案 0 :(得分:0)
如果我正确理解了您的代码,那么这里的问题是,您正在尝试使用另一个值pair.get(a)
来通过a
检索一个值(由于依赖于用户输入,该值可能甚至不存在!)。
假设您仍想实现此功能,则需要遵循以下原则。
// Get the key referenced by a (if exists)
var aKey = pair.entrySet()
.stream()
.filter(entry -> a.equals(entry.getValue()))
.map(Map.Entry::getKey)
.findFirst();
// If the key for value a does not exist, print incorrect input (you can handle this however you like), otherwise print original statement
if (aKey.isEmpty()) {
System.out.println("Incorrect input!");
} else {
System.out.println(a.equals(pair.get(values[retur])) ? "Correct answer." :
"Wrong answer. The correct one is \"" + pair.get(values[retur]) +
"\", you've just written the definition of \"" + pair.get(aKey.get()) + "\".");
}