Подскажите, пожалуйста, что не так в коде?
При вводе слова, которое не хранится в HashMap, должен выводить ответ по умолчанию, но вместо этого выводит null.
//класс, генерирующий ответы по умолчанию и заданные
import java.util.ArrayList;
import java.util.Random;
import java.util.HashMap;
import java.util.Map;
/**
* The responder class represents a response generator object.
* It is used to generate an automatic response to an input string.
*
* @author Michael Kölling and David J. Barnes
* @version 0.1 (2016.02.29)
*/
public class Responder
{
private Random random;
private ArrayList <String> responses;
private HashMap<String, String> answersMap;
/**
* Construct a Responder - nothing to do
*/
public Responder()
{
random = new Random();
responses = new ArrayList<>();
answersMap = new HashMap<>();
fillResponse();
fillResponseMap();
}
/**
* Generate a response.
* @return A string that should be displayed as the response
*/
//public String generateResponse()
//{
// int index = random.nextInt(responses.size());
// return responses.get(index);
//}
public String generateResponse(String word){
String answer = answersMap.get(word);
if (word != null){
return answer;
}else{
int index = random.nextInt(responses.size());
return responses.get(index);
}
}
/**
* The range of default responses when the programme does not know the answer.
*/
public void fillResponse(){
responses.add("Did you check the FAQ section on our website?");
responses.add("Could you describe the problem more detailed, please?");
}
/**
* The range of answers (values) and their keywords.
*/
public void fillResponseMap(){
answersMap.put("slow","Probably, our app is not compatible with the OS of your PC");
answersMap.put("call","We understand your frustration. Unfortunately, \n" +
"the phone call assistance is not supported. However, you can provide the \n" +
" following information about your problem in the email.");
answersMap.put("refund", "I am sorry to hear you are not happy with our app. \n" +
"As we can not give you a refund (more details in terms and conditions), \n" +
"I would glad to offer you an alternative. \n" +
"Please, send us an email with a refund object");
}
}
Вызывается код другим классом методом start()
public void start()
{
boolean finished = false;
printWelcome();
while(!finished) {
String input = reader.getInput();
if(input.startsWith("bye")) {
finished = true;
}
else {
String response = responder.generateResponse(input);
System.out.println(response);
}
}
printGoodbye();
}
Я полагаю Вам надо было написать:
if (answer != null){
Так как word в данном случае нет смысла проверять на null.
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости