Background: Extreme beginner in Java, so I am just getting comfortable with strings. I have been looking all over SO and Java API.
My problem: I am working on a little chat-bot project. The goal is when someone types in "I something you", the bot should return "Why do you something me?" With something being anything, such as "love" or to say "I love you", and have the bot return "Why do you love me?"
This, hopefully should also work with multiple words so if someone writes to the bot "I actually dislike you" the bot will respond with "Why do you actually dislike me?"
To do this I want to chop out the "I" and the "You", take whats left, and arrange it into a new sentence. I'm familiar enough to figure out how I would do it if I knew the string, but since anyone could input anything, as a beginner I am having trouble. Here's what I got:
public String getResponse(String statement)
{
String response = "";
if (findKeyword(statement, "I") >= 0
|| findKeyword(statement, "you") >= 0)
{
response = transformWhyDoYouStatement(statement);
}
return response;
}
private String transformWhyDoYouStatement(String statement)
{
// Remove the final period, if there is one
statement = statement.trim();
String lastChar = statement.substring(statement
.length() - 1);
if (lastChar.equals("."))
{
statement = statement.substring(0, statement
.length() - 1);
}
//String[] parts = string.split(" ");
len = statement.length;
String restOfStatement = statement.substring(psnOfYou + 3, psnOfMe).trim();
return "Why do you" + restOfStatement + " me?";
}
private int findKeyword(String statement, String goal, int startPos)
{
String phrase = statement.trim();
// The only change to incorporate the startPos is in the line below
int psn = phrase.toLowerCase().indexOf(goal.toLowerCase(), startPos);
// Refinement--make sure the goal isn't part of a word
while (psn >= 0)
{
// Find the string of length 1 before and after the word
String before = " ", after = " ";
if (psn > 0)
{
before = phrase.substring (psn - 1, psn).toLowerCase();
}
if (psn + goal.length() < phrase.length())
{
after = phrase.substring(psn + goal.length(), psn + goal.length() + 1).toLowerCase();
}
// If before and after aren't letters, we've found the word
if (((before.compareTo ("a") < 0 ) || (before.compareTo("z") > 0)) // before is not a letter
&& ((after.compareTo ("a") < 0 ) || (after.compareTo("z") > 0)))
{
return psn;
}
// The last position didn't work, so let's find the next, if there is one.
psn = phrase.indexOf(goal.toLowerCase(), psn + 1);
}
return -1;
}
Thank you all :)
Aucun commentaire:
Enregistrer un commentaire