【发布时间】:2018-04-05 03:36:49
【问题描述】:
我是一个非常业余的 Java 编码器,试图为 Uni 作业创建一个聊天机器人。我希望程序搜索我的动物数组,如果找到关键字,我可以使用数组的名称来给出特定的响应。到目前为止,我有两个问题(我想还会有更多问题)。
第一个-我的匹配系统仅在输入对话框中输入的唯一单词时才会识别关键字。例如,我只能说“狗”或“狗”,但我喜欢说“我想谈谈狗”,它会在句子中找到关键字。
第二个问题,如果关键字在第一个数组中没有找到,为什么不移动下一个数组?
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Chatbot {
public static void main(String[] args) {
String animal1[] = {"Dogs","Dawgs","dogs"};
String animal2[] = {"Cats"};
String animal3[] = {"Horses"};
String animal4[] = {"Lamas"};
String animal5[] = {"Ducks"};
String animal6[] = {"Pigs"};
String animal7[] = {"Cows"};
String animal8[] = {"Rabbits"};
String animal9[] = {"Chickens"};
String animal10[] = {"Mice"};
String response = JOptionPane.showInputDialog("Hi there, theses are all the animals i like to talk about ! :"
+ "\n-Dogs"
+"\n-Cats"
+"\n-Rabbits"
+"\n-Lamas"
+"\n-Hores"
+"\n-Ducks"
+"\n-Pigs"
+"\n-Cows"
+"\n-Chickens"
+"\n-Mice"
+"\n-Ask me somthing !");
int i;
boolean found=false; {
}
//DOGS
for(i=0; i<animal1.length;i++){
found=true;
// match your regex containing words from array against input
if(response.matches(".*\\b"+animal1[i]+"\\b.*")){
String dog = JOptionPane.showInputDialog("Dogs ? I love dogs, they taste great!\n" + "What other animals do you like ?");
//CATS
}
else
for(i=0; i<animal2.length;i++){
found=true;
if(response.matches(".*\\b"+animal2[i]+"\\b.*")){
String cat = JOptionPane.showInputDialog("Cats ? I love cats, they taste great!\n" + "What other animals do you like ?");
}
else
if(response.matches(".*\\b"+animal3[i]+"\\b.*")){
String horse = JOptionPane.showInputDialog("Horses ? I love Horses, they taste great!\n" + "What other animals do you like ?");
}
}
}
}
}
【问题讨论】:
-
String#contains将帮助您解决匹配问题。至于你的第二个问题......我会使用一个多维数组,但在任何一种情况下,编写一个方法,它需要一个String数组(作为源)和一个要搜索的术语,这样你可以使用search(animal1, "dogs");search(animal2, "dogs");...等...
标签: java arrays for-loop java.util.scanner