开发者

Simple if else statement not working [duplicate]

This question already has answers here: How do I compare strings in Java? (23 answers) Closed 9 years ago.

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"){
  T开发者_如何学Pythonoast.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"))

or

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.


You need to use equals method. Not == for comparison of strings. So, you should be doing -

if( Password.equals("a") )
{
    // ....
}    

string::equals reference


Try this:

if(Password.equals("a"))
{ 
...
}


== does a reference check, i.e. it checks if the two strings are physically the same object in memory. They might be (since Java optimises some strings so they are) but you should never rely on this.

equals() checks whether the strings are meaningfully equal, i.e. have the same characters, and this is what you want pretty much 100% of the time.


In Java...

Object comparison --> x.equals(y)
reference comparison --> x == y
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜