1

我正在开发一个用于分配任务的聊天机器人,它接收一个输入句子,在一个数组中查找某些触发器作品,并从中随机打印另一个响应数组的输出。我的问题是,当我输入诸如“否”之类的内容时,机器人会以错误数组的响应进行响应。我的 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);
}

和我的 doContain 方法:

    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 is inside of 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”(它是否定数组中的触发词),或者数组中的任何触发词作为输入,我会得到一个随机问题作为输出,而不是来自负响应数组。也打印了“doesContain = true”,但是它没有打印正确的响应。

4

1 回答 1

0

您需要在函数中添加返回值,否则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.

于 2015-04-23T23:14:46.070 回答