I am trying to create a chatbot as part of a tutorial, and have an answer method calling from an interface:
@Override public String answer(String question) {
if (hasAI() == false) {
return "Excellent";
}
else return QA.getOrDefault(question, "Interesting question.");
}
QA here is a simple immutable HashMap containing a bunch of questions and answers. So you enter a question, and get a corresponding answer if it has an AI, otherwise it just says "excellent". However, I am trying to call a method that stores records of the chat within that method, as per the tutorial.
public void addChatRecord(char type, String chat) {
if (type == 'Q' || type == 'A') {
chatRecords.add(type ":" chat);
}
else {
System.out.println("Wrong type of the chat.");
}
}
However, I am having some trouble trying to figure out how exactly to call the method addChatRecord within the answer method.
@Override public String answer(String question) {
if (hasAI() == false) {
return "Excellent";
}
else return QA.getOrDefault(question, "Interesting question.");
addChatRecord('A', String answer);
}
What should I put where String answer is? I'm trying to get the returned value of a method within that same method, and that is confusing me.
CodePudding user response:
Assign the answer to a variable, and use that variable as both your method parameter and return value:
@Override public String answer(String question) {
String answer = hasAI()
? QA.getOrDefault(question, "Interesting question.")
: "Excellent";
addChatRecord('A', answer);
return answer;
}
CodePudding user response:
Simply use a variable:
@Override public String answer(String question) {
String answer;
if (!hasAI()) {
answer= "Excellent";
}
else {
answer= QA.getOrDefault(question, "Interesting question.");
}
addChatRecord('A', answer);
return answer;
}