I have this matrix for a chat bot I am making in Java as a knowledge base of responses:
String[][] knowledgeBase={
{"hi","hello","howdy","hey"},//input 1; if you user inputs any of these,
{"hi","hello","hey"},//output 1; randomly choose between these as a response
{"how are you", "how r u", "how r you", "how are u"},//input 2; if you user inputs any of these,
{"good","doing well"},//output 2; randomly choose between these as a response
{"shut up","i dont care","stop talking"}//if input was in neither array, use one of these as a response
This is working fine when I have the matrix inside the java file. I made a JSON file (I am new to JSON so not very sure if I got the format right) that is similar to the matrix:
{
"0":{
"input":[""]
"output":["shut up","i dont care","stop talking"]
}
"1":{
"input":["hi","hello","howdy","hey"]
"output":["hi","hello","hey"]
}
"2":{
"input":["how are you", "how r u", "how r you", "how are u"]
"output":["good","doing well"]
}
}
This is my code for going through the matrix looking for an exact match of the input:
public void actionPerformed(ActionEvent e){
//get the user input
String quote=input.getText();
input.setText("");
if(!quote.equals("")){
addText("You:\t"+quote);
quote.trim();
while(quote.charAt(quote.length()-1)=='!' || quote.charAt(quote.length()-1)=='.' || quote.charAt(quote.length()-1)=='?'){
quote=quote.substring(0,quote.length()-1);
}
quote.trim();
byte response=0;
int j=0;
//check the knowledgeBase for a match or change topic
while(response==0){
//if a match is found, reply with the answer
if(inArray(quote.toLowerCase(),knowledgeBase[j*2])){
response=2;
int r=(int)Math.floor(Math.random()*knowledgeBase[(j*2)+1].length);
addText("\nPollockoraptor:\t"+knowledgeBase[(j*2)+1][r]);
}
j++;
//if a match is not found, go to change topic
if(j*2==knowledgeBase.length-1 && response==0){
response=1;
}
}
//change topic if bot is lost
if(response==1){
int r=(int)Math.floor(Math.random()*knowledgeBase[knowledgeBase.length-1].length);
addText("\nPollockoraptor:\t"+knowledgeBase[knowledgeBase.length-1][r]);
}
addText("\n");
}
}
public boolean inArray(String in,String[] str){
boolean match=false;
//look for an exact match
for(int i=0;i<str.length;i++){
if(str[i].equals(in)){
match=true;
}
}
return match;
}
How do I search through the JSON file with similar functionality? Can I also make numbers in the JSON files integers and not strings? Sorry if this is a very obvious question... I spent the past hour trying to figure out how to do this. Thank you for your help :)