Reputation: 41
The task is to ask for a definitions of some random cards. After I introduce the cards and I access this method, the value corresponding to the key is present and it still returns null.
pair.get(a) always printing null
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;
}
Upvotes: 0
Views: 1602
Reputation: 468
If I understand your code correctly the problem here is that you are trying to retrieve a value with pair.get(a)
using another value a
(which may not even exist since it depends on user input!).
Assuming you still want to achieve this functionality, you need to have something along these lines.
// 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()) + "\".");
}
Upvotes: 0