Java .equals 字符串的错误

战珠

我将编写一个程序,其中应该测试两个字符串是否相等。控制台输出两个相同的词,但 if 条件显示 nope。那是我的代码:

for (int i = 0; i < states.size(); i++){
    System.out.println("nextState(" + i + "): " + states.get(i).getName());
    System.out.println("rule: " + ruleSplitted.get(0));
    if(states.get(i).getName().equals(ruleSplitted.get(0))){
          actState = states.get(i);
    }
}

控制台说:

nextState(0): state1
rule: end 
nextState(1): end
rule: end 

我真的不知道那里出了什么问题。有人可以帮我吗?

格洛杰特

它出现states.get(i).getName()ruleSplitted.get(0)有一个尾随空格。您甚至可以在控制台的复制粘贴中看到它:

nextState(0): state1
rule: end 
nextState(1): end
rule: end 
         ^Right here

使用该String#trim()方法删除尾随空格:

if(states.get(i).getName().trim().equals(ruleSplitted.get(0).trim()))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章