[英]Similar String comparison fails
I am trying the following code in Android Studio. 我正在Android Studio中尝试以下代码。 When Debugging, I find out that even when Value of variable B is "(" my if statement does not execute and hovering over it, it shows it is false (please refer to image). The value of ScreenText in this case is "6(".
在调试时,我发现即使变量B的值是“(”,我的if语句也不会执行并且将其悬停在它上面,这表明它是错误的(请参阅图像)。在这种情况下,ScreenText的值为“ 6” (“。
Any help is appreciated. 任何帮助表示赞赏。
You should compare strings with the .equals()
method. 您应该使用
.equals()
方法比较字符串。 In this case, and to prevent a null pointer exception in case that your B variable is null, you should do so like this: 在这种情况下,并且为了防止B变量为null时出现null指针异常,您应该这样做:
if("(".equals(B)) {
...
}
The ==
operator is used for reference comparison, to check whether two object have the same reference. ==
运算符用于参考比较,以检查两个对象是否具有相同的参考。
You want to compare two String
s, use the boolean equals(String)
method. 您要比较两个
String
,请使用boolean equals(String)
方法。
if( "(".equals(B)) {
// your logic
}
Here comparing B
with "("
constant does not require you to make null
checks. 在这里,将
B
与常数"("
进行比较不需要您进行null
检查。
I think a more generic way to compare strings in Android is: 我认为在Android中比较字符串的更通用的方法是:
TextUtils.equals(B, "(");
And by the way, in your code 顺便说一下,在您的代码中
String.valueOf(c).toString();
toString() is redundant. toString()是多余的。
If you want to compare the value or contents of two strings then use .equals()
. 如果要比较两个字符串的值或内容,请使用
.equals()
。
if(string.equals("(")){
//Enter your code
}
But if you want to check that two object points to same reference then use ==
但是,如果要检查两个对象指向相同的引用,请使用
==
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.