字符串比较 - 机器人字符串、机器人

由网友(盛夏倾心空回忆)分享简介:我无法用下面的code来比较两个字符串:I'm unable to compare two strings using the following code:我有一个名为性别的字符串,有男或女作为它的值。I have a string named "gender" which will have "Male" o...

我无法用下面的code来比较两个字符串:

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.";

再次没有奏效。 是否有人可以告诉我如何使用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语句

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.

阅读全文

相关推荐

最新文章