[英]Why does songName[i]!= null evaluates to T when it should be F
I need to split the given array and print the string w/o WUB.我需要拆分给定的数组并打印没有 WUB 的字符串。 Below should print "ABC" but instead prints ",,ABC".下面应该打印“ABC”,而是打印“,,ABC”。 To be able to print ",,ABC" it needs to satisfy condition songName[i]!= null which should return F for those cases.为了能够打印“,,ABC”,它需要满足条件 songName[i]!= null 在这些情况下应该返回 F。 Still new to Java and programming at all对 Java 和编程还很陌生
import java.util.Arrays;
class Main {
public static void main(String[] args) {
String SongDecoder = "";
String song = "WUBWUBABCWUB";
String[] songName = song.split("WUB");
int cnt=0;
for (int i = 0; i < songName.length; i++){
if (songName[i]!= null){
if(cnt == 0){
SongDecoder = songName[i];
cnt+=1;
} else {
SongDecoder = SongDecoder+","+songName[i];
}
}
}
System.out.println(SongDecoder);
System.out.println(Arrays.toString(songName));
}
}
split()
returns empty String
s when there are no characters between two separators, not null. split()
当两个分隔符之间没有字符时返回空String
s,不为空。
Therefore, you should check for empty String
s in addition to your null
check:因此,除了null
检查之外,您还应该检查空String
s:
if (songName[i]!= null && !songName[i].isEmpty())
Or, actually, in this case, it would be enough to check that the String
is not empty (since it can't be null):或者,实际上,在这种情况下,检查String
是否为空就足够了(因为它不能为 null):
if (!songName[i].isEmpty())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.