Рандомные ответы по умолчанию и ответы, заданные с HashMap

236
23 июня 2018, 23:30

Подскажите, пожалуйста, что не так в коде? При вводе слова, которое не хранится в 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();
    }
Answer 1

Я полагаю Вам надо было написать:

if (answer != null){

Так как word в данном случае нет смысла проверять на null.

READ ALSO
Центрирование заднего фона

Центрирование заднего фона

Возник вопрос, как имея картинку и ставя её на задний фон получить положение её центра в центре экрана пользователя

203
table tfoot показывать на верху таблицы

table tfoot показывать на верху таблицы

Я читал в форуме о <tfoot> элементе, что он должен появиться после <thead> элементаИ все время его показывает внизу

220
Фон блока не растягивается вместе с контентом самого блока. Помогите

Фон блока не растягивается вместе с контентом самого блока. Помогите

У меня проблема с дивом "brya", я задаю ему background и все вроде бы хорошо, но фон не растягивается вместе с контентом который внутри дива, было пару...

208