字符串比较 - Android [英] String comparison - Android
本文介绍了字符串比较 - Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法使用以下代码比较两个字符串:
I'm unable to compare two strings using the following code:
我有一个名为gender"的字符串,它的值是Male"或Female".
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.";
同样,它没有用.谁能告诉我如何使用 if 语句比较字符串值.
Again, it didn't work. Can someone please tell me how to compare string values using the if statement.
推荐答案
试试这个
if(gender.equals("Male"))
salutation ="Mr.";
if(gender.equals("Female"))
salutation ="Ms.";
同时删除 if 语句中的 ;
(semi-colon )
Also remove ;
(semi-colon ) in your if statement
if(gender.equals(g1));
在 Java 中,新手最常遇到的错误之一是使用 == 比较字符串.你必须记住,== 比较的是对象引用,而不是内容.
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.
这篇关于字符串比较 - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文