Использование пользовательского ввода для итерации и заполнения LinkedHashMap, избегая дублирования без try-catch и ключей поиска - PullRequest
0 голосов
/ 25 мая 2020

Я пытаюсь написать карточную игру. Я использую LinkedHashMap для хранения карточек (слова, определения), определенных пользователем. Когда пользователь пытается добавить повторяющийся термин или определение, спрашивайте еще раз, пока пользователь не введет уникальный термин. Если cardDefinition и cardName верны, они сохраняются в Map с использованием flashcard.put(cardName, cardDefinition).

Затем прошу все определения карт в порядке добавления. Если определение неверно для текущего термина, но верно для другого, выведите исходный термин.

Код:

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        Map<String, String> flashcards = new LinkedHashMap<>();

        // Choose number of cards
        System.out.println("Input the number of cards:");
        int numberOfCards = Integer.parseInt(scanner.nextLine());

        while (flashcards.size() < numberOfCards) {
            for (int i = 0; i < numberOfCards; i++) {
                System.out.println("The card # " + (i + 1) + ":");
                String cardName = scanner.nextLine();
                if (flashcards.containsKey(cardName)) {
                    System.out.println("The card \"" + cardName + "\" already exists. Try again");
                    cardName = scanner.nextLine();
                } else {
                    System.out.println("The definition of the card #" + (i + 1) + ":");
                    String cardDefinition = scanner.nextLine();
                    if (flashcards.containsKey(cardDefinition)) {
                        System.out.println("The card \"" + cardDefinition + "\" already exists. Try again");
                        cardDefinition = scanner.nextLine();
                    }

                    flashcards.put(cardName, cardDefinition);
                }
            }
        }
        System.out.println(flashcards);
        System.out.println(flashcards.size());
        for (var entry : flashcards.entrySet()) {
            System.out.println("Print the definition of " + entry.getKey());
            String input = scanner.nextLine();
            if (input.equals(entry.getValue())) {
                System.out.println("Correct answer.");
            } else {
                if (flashcards.containsValue(input)) {
                    System.out.println("Wrong answer. The correct one is \"" + flashcards.get(input) + "\", you've just " +
                            "written the definition of \"" + entry.getKey() + "\"");
                }
            }
        }
    }
}

Требуемый пример вывода:

Input the number of cards:
> 2
The card #1:
> a brother of one's parent
The definition of the card #1:
> uncle
The card #2:
> a part of the body where the foot and the leg meet
The definition of the card #2:
> ankle
Print the definition of "a brother of one's parent":
> ankle
Wrong answer. The correct one is "uncle", you've just written the definition of "a part of the body where the foot and the leg meet".
Print the definition of "a part of the body where the foot and the leg meet":
> ???
Wrong answer. The correct one is "ankle".

Фактический результат:


Input the number of cards:
2
The card # 1:
blue
The definition of the card #1:
red
The card # 2:
white
The definition of the card #2:
black
{blue=red, white=black}
2
Print the definition of blue
red
Correct answer.
Print the definition of white
red
Wrong answer. The correct one is "null", you've just written the definition of "white

Думаю, я недалеко от правильного кода (надеюсь). Мне нужна помощь, пожалуйста.

1 Ответ

0 голосов
/ 25 мая 2020

Привет и добро пожаловать в stackoverflow.

Не лучше ли поставить «определение» в качестве ключа, а «описание» - в качестве значения? Так легче получить описание из определения. вы можете сделать flashcards.get("ankle") и получить a part of the body where the foot and the leg meet

. Ваш println внизу выглядит неправильно. Я думаю, это должно быть:

System.out.println("Wrong answer. The correct one is \"" + entry.getValue() + "\", you've just " + "written the definition of \"" + alternate.getKey() + "\"");
где вы получаете alternate отсюда:

if (flashcards.containsValue(input)) {
    Entry<String, String> alternate = null;
    for (var alt : flashcards.entrySet()) {
        if (alt.getValue().equals(input)) {
            alternate = alt;
            break;
        }
    }
    System.out.println(
            "Wrong answer. The correct one is \"" + entry.getValue() + "\", you've just " +
            "written the definition of \"" + alternate.getKey() + "\""
        );
}
...