有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java聊天机器人从错误的响应数组返回

我正在为一个任务开发一个聊天机器人,它接收一个输入句子,在一个数组中查找某个触发器,然后从中随机打印另一个响应数组的输出。我的问题是,当我键入诸如“否”之类的内容时,bot会以错误数组的响应进行响应。 我的getResponse方法:

    public static String getResponse(String input) {
    if(doesContain(input, negatives)){
        getRandResponse(negResponse);
    }
    //If none of the criteria is met, the bot will ask a random question from the questions array.
    return getRandResponse(quesResponse);
}

而我的doesContain方法:

    public static boolean doesContain (String input, String[] tArr){
    //Where tArr is an array of trigger words, and input is the users input
    for(String i: tArr){
        if(indexOfKeyword(input, i) != -1){
            System.out.println("doesContain = true");
            return true;
        }
    }
    return false;
}

indexOfKeyword方法检查触发字是否位于另一个字的内部,例如no位于know的内部,如果该字不在另一个字的内部,则返回该字的索引,否则返回-1。以下是indexOfKeyword方法:

    public static int indexOfKeyword( String s, String keyword ) {

    s.toLowerCase();
    keyword.toLowerCase();

    int startIdx = s.indexOf( keyword );

    while ( startIdx >= 0 ) {
        String before = " ", after = " ";

        if ( startIdx > 0 ) {
            before = s.substring(startIdx - 1, startIdx);
        }
        int endIdx = startIdx + keyword.length();

        if ( endIdx < s.length() ){
            after = s.substring(endIdx, endIdx + 1);
        }
        if ((before.compareTo("a") < 0 || before.compareTo("z") > 0) && (after.compareTo("a") < 0 || after.compareTo("z") > 0)) {
            return startIdx;
        }
        startIdx = s.indexOf(keyword, startIdx + 1);
    }
    return -1;
}

最后,我的getRandResponse方法:

public static String getRandResponse(String[] respArray){return respArray[random.nextInt(respArray.length)]; }

现在我的问题是,如果我键入“no”(否定数组中的一个触发字),或者数组中的任何触发字作为输入,我会得到一个随机问题作为输出,而不是NergResponse数组的响应。打印“doesContain=true”也是一样,但是它不会打印正确的响应


共 (1) 个答案

  1. # 1 楼答案

    您需要向函数添加一个返回,否则来自negResponse数组的响应将永远不会返回,它将转到下一行并返回来自quesResponse的响应:

    public static String getResponse(String input) {
        if(doesContain(input, negatives)){
            // add return here:
            return getRandResponse(negResponse);
        }
        //If none of the criteria is met, the bot will ask a random question from the questions array.
        return getRandResponse(quesResponse);
    }
    

    此外,无论发生什么情况,doesContain函数始终返回true。第二个return语句应该改为return false