-2

I am new to app development and I have a problem with coding in android studio. I want to compare an input text with a string in the string array. For some reason it won't work. When i try the java code in eclipse it works.

I already run the debugger and the inputmessage is "Banana". The debugger also shows that message = "Banana" when it is in CheckAnswer(message). But for some reason the function isn't returning "Right". It returns "wrong"

I hope somebody can help me.

Here is my code:

public void sendMessage(View view) {
    // Do something in response to button
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    String message2 = CheckAnswer(message);
    intent.putExtra(CORRECT_MESSAGE, message2);
    startActivity(intent);

}

public static String CheckAnswer(String string) {
    String rightanswer[] = {"Apple", "Banana", "Coconut"};
    String answer = null;
    for (int i = 0; i <= rightanswer.length-1; i++) {
        if (string == rightanswer[i]) {
            answer =  "Right!!";
            break;
        }
        else answer = "Wrong.";
    }
    return answer;
}
L.B
  • 139
  • 2
  • 12

2 Answers2

2

The correct way of comparing two strings is with equals() function not ==

So Change :

       if (string == rightanswer[i]) {
            answer =  "Right!!";
            break;
        }

to:

        if (string.equals(rightanswer[i])) {
            answer =  "Right!!";
            break;
        }
Pooya
  • 6,083
  • 3
  • 23
  • 43
1

When you are comparing Strings in Java, it is best to use the String's equals()method which looks like this:

if(someValue.equals(somethingElse){}

I hope this helps!

Eenvincible
  • 5,641
  • 2
  • 27
  • 46