Search code examples
javaandroidautomationappiumchatbot

How to get user input from element and provide a accurate response?


I am trying to make a chat bot on my android phone, right now, I want to make it so that if someone says "Hey man", the bot responds with "Sup man!" I want to be able to add more of these cases as well.

I tried using this method here

String A = "Hey man";

MobileElement element = (MobileElement) 
driver.findElement(By.id("com.samsung.android.app.memo:id/editText1"));
String text = element.getText();
System.out.println(text);

if (text == A) {

System.out.println("Sup man!");

} else {

System.out.println("No response available");

}

But this doesn't work because text = element.getText() and not "Hey man". Can anyone point me in the right direction on how to do this correctly?


Solution

  • You are comparing your Strings, text and A, using == which is the wrong way to compare Strings — it tests if the two String objects are the same object, not just that they contain the same text.

    You want to compare using if (text.equals(A)) or, if you want to match without regard to case, you'd use if (text.equalsIgnoreCase(A))

    With .equals() you are looking for "Hey man", but if the person types "hey man" those won't match and the bot won't respond just because of the upper- vs. lower-case "Hey" vs. "hey". If you want to match the phrase no matter how someone types it you would use .equalsIgnoreCase()

    If you want to have multiple phrases you could use an array, or some kind of Collection and you would loop over it to find a match, something like

    for (final String phrase : phrases) {
        if (phrase.equalsIgnoreCase(text)) {
            System.out.println(some_text_for_that_phrase);
        }
    }
    

    ...where I'm using phrases instead of A because it's more descriptive.

    If you want different responses for each possible matched phrase you would probably want your Collection to be a Map where the map key is the phrase you want to match and the map value is the response you would give. In that case you would get the user text and just use it directly to get the response from the map without having to loop

    final String response = phraseMap.get( userText.toLowerCase() );
    if (response != null) {
        System.out.println(response);
    }
    

    You can't compare ignoring case with map keys, so you'd want to lowercase every key phrase you put in the map, then lowercase the user input so it matches whats in the map. The response values may, of course, be whatever mix of case you want.

    How you fill the map with the key phrases and responses would be another separate question.