我有
String x = g.substring(0, 1);
if (x == "S") {
stuff
}
我有一个字符串“Safety”,但“stuff”没有运行,我的手表显示 x value = S and x=="S"
= false。
==
用于identity
比较,它检查两个reference
点是否指向同一个对象(在您的情况下,对象是String
)。
您应该使用该equals
方法来比较字符串的内容:
if (x.equals("S"))
x=="S"
这比较引用而不是您应该使用的字符串相等性"S".equals(x)
。
改用equals()
String 类的方法,而不是==
.
if(x.equals("S"))
== 检查引用而不是值。
您需要String.equals
用于比较字符串内容。==
运算符用于比较对象引用。
Switching the positions of the arguments will avoid a NullPointerException
:
if ("S".equals(x))
You should use the .equals
method to compare Strings (and any non-primitives in general).
if (x.equals("S")) {
//stuff
}
In Java equals()
checks equality and ==
checks identity.
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()
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
}