14

Simple if otherwise the instruction does not work

 4 years ago
source link: https://www.codesd.com/item/simple-if-otherwise-the-instruction-does-not-work.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Simple if otherwise the instruction does not work

advertisements

This question already has an answer here:

  • How do I compare strings in Java? 23 answers

I have a simple password protection. I do it like this:

EditText editText1 =  (EditText) findViewById(R.id.editText1);
String Password = editText1.getText().toString();
if(Password == "a"){
  Toast.makeText(getApplicationContext(), "Success" + Password, Toast.LENGTH_SHORT).show();
} else {
  Toast.makeText(getApplicationContext(), "Failure" + Password, Toast.LENGTH_SHORT).show();
}

I have edittext and button. If user is typing in "a", toast should say success. But it is always saying failure. I don't understand what is wrong in my code...


In Java, using == for non-primitive expressions will always compare object references. You're asking whether Password refers to the exact same object as the string literal "a".

Use either:

if (Password.equals("a"))

if ("a".equals(Password))

These will call the String.equals(Object) override, which determines whether two references refer to equal String objects - i.e. the same logical sequence of characters.

The former will throw an exception if Password is null; the latter won't. Don't treat this as a suggestion to always use the latter form - if Password shouldn't be null, then an exception may well be better than continuing in an unexpected state.

I'd also encourage you to be consistent with your variable names - typically local variables are camelCased, so you'd use password instead of Password.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK