Search code examples
javainterfacehashmapchatbotabstract

How do I override methods intended to return certain strings from an immutable HashMap?


I am trying to program a Java-based chatbot for an assignment. I have an abstract interface called Chatty. It has a set, immutable map of questions and answers:

import java.util.HashMap;
import java.util.Map;

public interface Chatty {

    // Chat levels
    int LEVEL_MIN = 1;
    int LEVEL_MAX = 3;

    // Question & answer repertoires
    Map<String,String> QA = Map.of(
            "Hello, how are you?", "I'm great, thanks.",
            "What are you?", "I am a chatbot",
            "Do you have a hobby?", "I like chatting with you.",
            "Can you tell a joke?", "You are very funny!",
            "What is the capital of UK?", "London",
            "Do you like Java?", "Yes of course.",
            "Are you a robot?", "Yes I’m a robot, but I’m a smart one!",
            "Do you get smarter?", "I hope so."
    );


    /**
     * Ask a question
     *
     * @return the question
     */
    String question();

    /**
     * Answer a given question by a given robot
     *
     * @param question A given question
     * @return An answer
     */
    String answer(String question);

}

I have another class, ChatBot, and my task is to implement this interface. As it is an abstract interface, I naturally have to override String question and String answer(String question).

public class ChatBot implements Chatty {
    
    @Override public String question() {
        return ;
    }
    
    @Override public String answer(String question) {
        return ;
    }

However, I'm not sure how exactly I return the question when there are only certain questions permitted. In other words, how do I take those specific strings out of the Hashmap?


Solution

  • What exactly does method Chatty.question() do? It seems to me, that it should return set of questions, that user is able to ask the bot. In that case it should look like this

    @Override
    Set<String> getQuestions() {
        return QA.keySet();
    }
    
    @Override
    String getAnswer(String question) {
        return QA.getOrDefault(question, "I don't know, how to answer that question");
    }