对于我的AP CompSci项目,我需要编写一个聊天机器人。
第一步,它需要检测某些关键字,并做出适当的回应
然而,即使statement
参数不包含" no",responce
总会最终设置为"为什么会这样消极?&#34 ;。我不知道为什么会发生这种情况,但我认为它与我使用的java contains()
方法有关
我的代码列在下面
static String[] family = {"mother", "father", "brother", "sister"};
static String[] pets = {"cat", "dog", "parrot", "lizard"};
static String[] family = {"mother", "father", "brother", "sister"};
static String[] pets = {"cat", "dog", "parrot", "lizard"};
public static String getResponse(String statement) {
String response = "Interesting. Tell me more.";
for (int i = 0; i < family.length; i++) {
if (statement.contains(family[i])) {
response = "Tell me more about your family.";
}
}
for (int i = 0; i < pets.length; i++) {
if (statement.contains(pets[i])) {
response = "Tell me more about your pets.";
}
}
if (statement.contains("no")); {
response = "Why so negative?";
}
return response;
}
public static void main(String[] args) {
System.out.println(getResponse("yes"));
//This will still act like the input is "no"
}
我为可怕的格式道歉,我对StackOverflow不太好
感谢所有帮助 - 我不知道为什么它没有输出&#34;有趣,告诉我更多&#34;喜欢它应该
谢谢!
答案 0 :(得分:3)
你的if语句后面有一个分号:
if (statement.contains("no"));
{
response = "Why so negative?";
}
这意味着if块的主体为空,即等效于以下代码:
if (statement.contains("no")) {
}
{
response = "Why so negative?";
}
删除分号,它应该按预期工作。