简体   繁体   English

Java .equals 字符串的错误

[英]Java .equals bug for a string

I'm going to code a program where should be test two strings to equality.我将编写一个程序,其中应该测试两个字符串是否相等。 The console puts two equal words out but the if condition says nope.控制台输出两个相同的词,但 if 条件显示 nope。 That's my code:那是我的代码:

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);
    }
}

That says the console:控制台说:

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

I really don't know whats wrong there.我真的不知道那里出了什么问题。 Could somebody help me please?有人可以帮我吗?

It appears either states.get(i).getName() or ruleSplitted.get(0) has a trailing white space.看起来states.get(i).getName()ruleSplitted.get(0)都有一个尾随空格。 You can even see it in your copy paste of the console:您甚至可以在控制台的复制粘贴中看到它:

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

Use the String#trim() method to remove the trailing whitespace(s):使用String#trim()方法删除尾随空格:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM