0

I am not sure why it is not working. Even the condition is true, when I am clicking on submit button it is running the else statements and returning 0. Please help.

XML Code:

<EditText
    android:id="@+id/dog_textView"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:layout_marginTop="72dp"
    android:layout_marginRight="8dp"/> 
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Submit"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    int playerScore = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void submitOrder(View v){

        EditText editText = (EditText) findViewById(R.id.dog_textView);
        String answer = editText.getText().toString().toUpperCase();
        if (answer == "DOG"){
            playerScore = playerScore + 2;
            Toast toast = Toast.makeText(MainActivity.this,"Your player score is: "+ playerScore ,Toast.LENGTH_SHORT);
            toast.show();
        } else {
            Toast toast = Toast.makeText(MainActivity.this,"Your player score is: "+ playerScore ,Toast.LENGTH_SHORT);
            toast.show();
        }
    }

}
  • Don't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Nov 03 '17 at 01:54
  • So not `if (answer == "DOG"){` but rather `if (answer.equals("DOG")) {` or `if (answer.equalsIgnoreCase("DOG")) {` – Hovercraft Full Of Eels Nov 03 '17 at 01:55
  • Thank you so much for your support and reference. It works. –  Nov 03 '17 at 01:58
  • Could you please tell me the difference between if (answer.equals("DOG")) and (answer.equalsIgnoreCase("DOG")) –  Nov 03 '17 at 01:59
  • @Lucifer check this link https://www.javatpoint.com/java-string-equalsignorecase equalsIgnoreCase ignores the case during comparison – kimkevin Nov 03 '17 at 02:01
  • Awesome, I get it now. Thanks... –  Nov 03 '17 at 02:05
  • The method name is self-explanatory, isn't it? – Hovercraft Full Of Eels Nov 03 '17 at 02:10
  • When we use == , the Reference of object is compared not the actual objects. – Shahzain ali Nov 03 '17 at 04:46

0 Answers0