How to refer to a String through various values in Java (Android)?

Asked

Viewed 78 times

1

I made a chatbot/virtual assistant and I want it to answer the same thing for different words, example: if I write "Hi" or write "Hello" it return the same answer: "Hello, how can I help".

public void assistente(View view) {
    if (caixa.getText().toString().equals(cumprimento) {

        resposta.setText("Olá, como posso te ajudar?");
        rosto.setImageResource(R.drawable.normal);

    } 

resposta.setText("Olá, como posso te ajudar?"); 

} 

String cumprimento = "Olá"; //Nessa parte eu quero colocar outros valores 

I use Android Studio 3.0.1. I am very beginner in programming, please explain in the easiest way possible. Thank you very much!

  • Your question is not clear enough ? Just have that question and answer ? How would it work if the person wrote something else?

2 answers

0

Use the Class Stringbuilder https://developer.android.com/reference/java/lang/StringBuilder.html

StringBuilder sb = new StringBuilder();

public void assistente(View view) {
    if (caixa.getText().toString().equals(cumprimento) {

        resposta.setText("Olá, como posso te ajudar?");
        rosto.setImageResource(R.drawable.normal);

    } 

resposta.setText("Olá, como posso te ajudar?"); 

sb.append(" Outro texto ").append("Ok");

} 

sb.append("Olá").append(" Teste"); //Nessa parte eu quero colocar outros valores 

*According to your logic you build your answer. *

  • I don’t understand how I put it in the code because it claims there are too many errors

  • Puts Stringbuilder within the scope of the class if you want to use it in other methods.

0

If I understood what you meant, you could do something like this:

    ArrayList<String> cumprimentos = new ArrayList<String>();
    cumprimentos.add("oi");
    cumprimentos.add("blz");
    cumprimentos.add("Olá");

 public void assistente(View view) {
 if (cumprimentos.contains(caixa.getText().toString())) {

    resposta.setText("Olá, como posso te ajudar?");
    rosto.setImageResource(R.drawable.normal);

  } 

    resposta.setText("Olá, como posso te ajudar?"); 

} 
  • Understood and even worked, thanks! But when I put a complement to more like, ex.: if (greetings.contains(box.gettext().toString()) + " ,all right") it performs, but does not work.

  • If your logic is to take a word of "Hello", "Hi", etc. within a sentence you can do so: String sentence = "Check this Answer and you can find the keyword with this code"; String search = "keyword"; if ( sentence.toLowerCase(). indexof(search.toLowerCase()) != -1 ) { /rest of logic/ }.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.