0

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;
        }
sHIFT0O
  • 41
  • 3
  • I guess the error comes from `pair.get(a)`? The key `a` is not guaranteed to be in your dictionary, as tar as I can tell. It does not come from the `values` array. `a` is what was typed on the console. This can be anything. Also, if your keys in the dictionary are not strings then `pair.get(a)` will always return `null`. – Daniel Junglas Apr 08 '20 at 16:19
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include the source code you have as a [mcve], which can be compiled and tested by others. – Progman Apr 08 '20 at 18:22

1 Answers1

0

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())  + "\".");
}
Matthew Formosa
  • 468
  • 3
  • 9