我遇到一个问题,在查找子字符串时 .contains()
未返回 true
。
请参阅下面的代码 fragment 和图像,其中显示了以下代码的变量值。我遇到的问题是表达式返回 false
,而我认为它显然应该是 true
。
if (this.fileName.toLowerCase().contains(extension.toLowerCase())){
return true;
}
我今天遇到了这个问题,在搜索网络后我看不到任何明显的情况。
我已经尝试使用文字进行相同的操作,但仍然无法评估为 true:
if ("Android App Image.jpg".toLowerCase().contains("jpg".toLowerCase())){
return true;
}
我已经将其进一步分割,因此结果是 boolean 值:
boolean result = ("Android App Image.jpg".contains("jpg"));
if (result) {
return true;
}
结果是 true,所以 .contains
不是问题,而是我的 if()
没有将 boolean 值评估为 true 并且不会导致返回 true
执行。
我现在认为这是我的 while 循环的问题(完整功能如下)。枚举是否异步运行?
public boolean isImage(){
String[] imageExtensions = {"jpg", "png", "bmp", "gif"};
for (String extension: imageExtensions) {
if (this.localFileURLString != null && this.localFileURLString.toLowerCase().contains(extension)){
return true;
}
boolean result = ("Android App Image.jpg".toLowerCase().contains("jpg".toLowerCase()));
if (result) {
return true;
}else{
Log.i("TEACH", "If evaluated false");
}
}
return false;
}
更新 1/2:
我已经用硬编码文字修剪了整个函数,并且不再使用快速枚举,当我期望它返回 true
时,它仍然返回 false
:
public boolean isImage(){
String[] imageExtensions = {"jpg", "png", "bmp", "gif"};
for (int x = 0; x < imageExtensions.length; x++) {
// String extension = imageExtensions[x];
boolean result = ("Android App Image.jpg".toLowerCase().contains("jpg".toLowerCase()));
if (result) {
return true;
}else{
Log.i("TEACH", "If evaluated false");
}
}
return false;
}
该函数不返回true
,或者执行“如果评估为假”
日志,它只是直接跳转到函数的最后一行( return false;
) 在计算 if (result) {
行之后...就好像 if
打破了循环。
更新 2/2:
很简单,即使是函数中最简单的 if
语句也会导致代码跳转到函数的最后一行并返回 false
。例如:
if(true == true){
return true
}
在 Debug模式下单步执行时会发生这种情况,并且编码日志在未附加到错误器时也会显示相同的结果。
从函数返回后,一切都正常进行。没有错误或警告。
重新安装 Android Studio、尝试不同的模拟器和物理 Android 设备都没有解决问题。
重命名该函数未能解决问题。
将函数的返回类型从 boolean
更改为 Boolean
确实解决了该问题。
我很清楚这些类型的差异,但我仍然很困惑为什么会出现这个问题。我只能假设以这种方式更改方法签名是在编译时发生的一些奇怪的事情。
我暂时保留这个问题,因为即使更改返回类型“解决”了我的问题,我仍然不满意,我会知道为什么......可能永远不会。
希望对这类问题更了解的人能够启发一下!
最佳答案
为什么不尝试使用:
if (this.fileName.toLowerCase().contains(extension.toLowerCase()==true){
}
关于Java .contains() 的行为不符合我的预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51211335/