Vladyslav Vladyslav - 3 months ago 7
Android Question

Comparing two equal strings but get incorrect result

So I need to compare my string with string that user inputs in EditText.
I input same string but Java thinks that this is two different strings.
I checked on spaces and didn't find them.

private void checkEditTexts(){
...
String userAnswer = editTextAnswer.getText().toString().toLowerCase();
String rightAnswer = getResources().getString(R.string.question3_answer1).toLowerCase();

Log.v("checkET.userAnswer", "userAnswer = [" + userAnswer + "] rightAnswer = [" + rightAnswer + "]" );

if(userAnswer == rightAnswer) {
points++;
Log.v("checkEditTexts()", "POINTS++: " + points);
}else{
points--;
Log.v("checkEditTexts()", "POINTS--: " + points);

}
...
}


Logcat:

08-29 16:47:27.494 16583-16583/....V/checkET.userAnswer: userAnswer = [song 2] rightAnswer = [song 2]

08-29 16:47:27.494 16583-16583/... V/checkEditTexts(): POINTS--: 2

08-29 16:47:27.494 16583-16583/....V/checkEditTexts(): POINTS--: 1

08-29 16:47:27.494 16583-16583/....V/checkEditTexts(): POINTS: 1


You can see that userAnswer and rightAnswer are equal and it should perform
points++
, but instead it does
points--


Sorry for bad English.

Answer

use equels or equalsIgnoreCase. == compare the the reference type not value. but equels and equalsIgnoreCase checks for value not reference.

if(userAnswer.equalsIgnoreCase(rightAnswer)) {
points++;
    Log.v("checkEditTexts()", "POINTS++: " + points);
}else{
    points--;
    Log.v("checkEditTexts()", "POINTS--: " + points);

}