String comparison - Android

2019-01-02 18:32发布

I'm unable to compare two strings using the following code:

I have a string named "gender" which will have "Male" or "Female" as its value.

if(gender == "Male")
   salutation ="Mr.";
if(gender == "Female")
   salutation ="Ms.";

This didn't work, so I tried the following:

String g1="Male";
String g2="Female";
if(gender.equals(g1))
   salutation ="Mr.";
if(gender.equals(g2))
   salutation ="Ms.";

Again, it didn't work. Can someone please tell me how to compare string values using the if statement.

16条回答
其实,你不懂
2楼-- · 2019-01-02 18:47

This one work for me:

 if (email.equals("fahim@gmail.com") && pass.equals("123ss") ){
        Toast.makeText(this,"Logged in",Toast.LENGTH_LONG).show();
    }
    else{

        Toast.makeText(this,"Logged out",Toast.LENGTH_LONG).show();
    }
查看更多
人间绝色
3楼-- · 2019-01-02 18:49

Actually every code runs well here, but your probleme probably come from your gender variable. Did you try to do a simple System.out.println(gender); before the comparaison ?

查看更多
深知你不懂我心
4楼-- · 2019-01-02 18:51

Try it:

if (Objects.equals(gender, "Male")) {
    salutation ="Mr.";
} else if (Objects.equals(gender, "Female")) {
    salutation ="Ms.";
}
查看更多
其实,你不懂
5楼-- · 2019-01-02 18:52

Try this

if(gender.equals("Male"))
 salutation ="Mr.";
if(gender.equals("Female"))
 salutation ="Ms.";

Also remove ;(semi-colon ) in your if statement

if(gender.equals(g1));

In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object references, not the content.

查看更多
美炸的是我
6楼-- · 2019-01-02 18:55

try this.

        String g1 = "Male";
        String g2 = "Female";
        String gender = "Male";
        String salutation = "";
        if (gender.equalsIgnoreCase(g1))

            salutation = "Mr.";
        else if (gender.equalsIgnoreCase(g2))

            salutation = "Ms.";
        System.out.println("Welcome " + salutation);

Output:

Welcome Mr.
查看更多
临风纵饮
7楼-- · 2019-01-02 18:56

Your gender == "Male" is actually comparing the object references for the object gender and a different object Male. What you have to use is the .equals() method to compare the value of the objects.

查看更多
登录 后发表回答