我正在为一项任务开发一个聊天机器人,它接受一个输入句子,在一个数组中查找某些触发器,然后随机打印另一个响应数组的输出。我的问题是,当我输入“否”之类的内容时,机器人会使用错误的数组进行响应。 我的 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”(这是负数数组内的触发词)或数组中的任何触发词作为输入,我会得到一个随机问题作为输出,而不是来自 negResponse 数组的响应。还打印了“doesContain = true”,但它没有打印正确的响应。
最佳答案
您需要向函数添加返回,否则 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
。
关于java - 聊天机器人从错误的响应数组中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29835879/