字符串比较解决方案在java不工作



我知道这个问题已经被问死了,但我已经尝试了所有的解决方案,给出了这个问题,我的if语句仍然没有执行。我的代码是这样的:

String s = "Something*like*this*";
String[] sarray = s.split("\*");
for(int i = 0; i < sarray.length; i++) {
  if(sarray[i].equals("this")) {
    //do something
  }
}

这确实像预期的那样工作

for (String token : "Something*like*this*".split("\*")) {
    if (token.equals("this")) {
        System.out.println("Found this");
    }
}

if 将在这里执行。

在drJava交互窗格(或您最喜欢的IDE窗格)中测试这一点,单独的部分(检查它们每个工作)。

Welcome to DrJava.  Working directory is C:JavaProjects
> String s = "Something*like*this";
> String[] sarray = s.split("\*");
> sarray[0]
"Something"
> sarray[1]
"like"
> sarray[2]
"this"
> sarray[3]
java.lang.ArrayIndexOutOfBoundsException
> sarray.length
> 3 
> sarray[1].equals("this")
false
> 

最新更新