0

我有

String x = g.substring(0, 1);
if (x == "S") {
    stuff
}

我有一个字符串“Safety”,但“stuff”没有运行,我的手表显示 x value = S and x=="S"= false。

4

9 回答 9

2

==用于identity比较,它检查两个reference点是否指向同一个对象(在您的情况下,对象是String)。

您应该使用该equals方法来比较字符串的内容:

if (x.equals("S"))
于 2012-10-14T20:26:21.730 回答
1

x=="S"这比较引用而不是您应该使用的字符串相等性"S".equals(x)

于 2012-10-14T20:26:28.023 回答
1

改用equals()String 类的方法,而不是==.

于 2012-10-14T20:26:31.907 回答
0
if(x.equals("S"))

== 检查引用而不是值。

于 2012-10-14T20:26:31.830 回答
0

您需要String.equals用于比较字符串内容。==运算符用于比较对象引用。

Switching the positions of the arguments will avoid a NullPointerException:

if ("S".equals(x))
于 2012-10-14T20:27:03.953 回答
0

You should use the .equals method to compare Strings (and any non-primitives in general).

if (x.equals("S")) {
    //stuff
}
于 2012-10-14T20:27:04.023 回答
0

In Java equals() checks equality and == checks identity.

于 2012-10-14T20:27:48.820 回答
0

Many problems...

  • Your variable x is a String! You shouldn't use == operator with that, use .equals() instead

  • Also, while you're at it, you should use .equalsIgnoreCase() to ignore case.

  • By the way, I should note that there is the String.charAt(int) function too, which returns the character at the specified place...

But if you would like to select all Strings (your question didn't reveal your original intentions why and what you are trying to achieve), but I'd look into regular expressions, and using String.matches()

于 2012-10-14T20:29:13.143 回答
0

Why don't you use the charAt function and do it like this:

    char x = g.charAt(0);
    if (x == 'S') {
       // Stuff
    }

If you don't want to use char, use the equals method in the if block comparison as:

   String x = g.substring(0, 1);
   if (x.equals("S")) {
      // stuff
   }
于 2012-10-14T20:31:53.577 回答