java 为什么我的字符串比较不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1530864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 16:57:19  来源:igfitidea点击:

Why doesn't my string comparison work?

java

提问by cc.

Ok, this is stupid, but wtf is going on?

好吧,这很愚蠢,但是wtf是怎么回事?

I have a String variable in a servlet, which takes the value of a parameter and based on that value I make a test to do something, but the ifis not working. What is the problem?

我在 servlet 中有一个 String 变量,它获取参数的值,并根据该值进行测试以执行某些操作,但该变量if不起作用。问题是什么?

 String action = request.getParameter("action");
    System.out.println("Action: " + action);
// I put 2 ifs to be sure, but not even one is working
    if(action.equals("something"))
            {
                System.out.println("hey");            
            }
    if(action.trim() == "something")
            {
                System.out.println("hey");
            }

On the console, the System.out.println shows me that the value of action is "something"

在控制台上, System.out.println 向我显示 action 的值是“某物”

Action: something

回答by Daniel Rikowski

Your second comparison is wrong. You should also use equalsinstead of ==, like this:

你的第二个比较是错误的。您还应该使用equals代替==,像这样:

if (action.trim().equals("something"))

The ==operator compares referencesof (String) objects and under normal circumstances equalstrings don't automatically have the same reference, i.e. they are different objects. (Unless both are internalized, but normally you shouldn't consider it)

==运算符比较引用的(字符串)对象和正常情况下等于字符串不自动具有相同的参考,也就是说,它们是不同的对象。(除非两者都被内化了,但通常你不应该考虑它)

Other than that your example works fine and the first comparison is valid. Try fixing the second comparison. If it works, you found your problem. If not, try using a debugger and double-check everything.

除此之外,您的示例工作正常并且第一次比较有效。尝试修复第二个比较。如果它有效,你就发现了你的问题。如果没有,请尝试使用调试器并仔细检查所有内容。

PS: When comparing literal strings with dynamic string objects, it's good practice to call the equalsmethod on the literal string:

PS:比较文字字符串和动态字符串对象时,最好equals在文字字符串上调用方法:

"something".equals(action)

That way you can avoid NullPointerExceptions when the string object is null.

这样您就可以在字符串对象为空时避免 NullPointerExceptions。

回答by Pete Kirkham

Your second condition is unlikely ever to be true - you're testing whether the string object created by trimming actionis the same object as the string literal "something". This will only be true if actionis set to that same literal value elsewhere. Use "something".equals( action.trim() )instead.

您的第二个条件不太可能成立 - 您正在测试通过修剪创建的字符串对象是否action与字符串文字相同"something"。只有在action其他地方设置为相同的文字值时,这才会为真。使用"something".equals( action.trim() )来代替。

Your first condition would be true the characters in the actionstring are the characters "something". If it's not true, then it doesn't. Assert it in a test, log it, print it or look at it in a debugger.

您的第一个条件是 trueaction字符串中的字符是 characters "something"。如果这不是真的,那就不是。在测试中断言它,记录它,打印它或在调试器中查看它。

If you print a string for debugging, use something like System.out.println ( "String = >" + string + "<" );so that it's obvious if there are any trailing spaces.

如果您打印一个字符串进行调试,请使用类似的内容,System.out.println ( "String = >" + string + "<" );以便很明显是否有任何尾随空格。

回答by JCasso

String comparison in Java cannot be done by ==.

Java 中的字符串比较不能由==.

You have to use String.equals()or String.compareTo()-

你必须使用String.equals()String.compareTo()-

By the way, String.compareTo()returns 0whereas String.equals()returns truewhen two strings are equal.

顺便说一下,当两个字符串相等时String.compareTo()返回0String.equals()返回true

See: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#equals(java.lang.Object)

参见:http: //java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#equals(java.lang.Object)

回答by Chris R

My guess is that you've got trailing or leading spaces which don't show in the println.

我的猜测是你有没有在 println 中显示的尾随或前导空格。

Combine this with the fact that you're using action.trim() == 'something'means this test won't work either.

将此与您正在使用的事实相结合action.trim() == 'something'意味着此测试也不起作用。

Switch this to .equals("something")as suggested by others and it might work.

.equals("something")按照其他人的建议将其切换为它可能会起作用。

回答by A_M

You can better protect against nulls by switching the if clauses around to have the string literal first.

您可以通过切换 if 子句以首先使用字符串文字来更好地防止空值。

But since you also seem to want to protect against whitespace on the parameter value, you could also do a null safe trim of the parameter value using StringUtils.trimToEmptyfrom Apache Commons Lang:

但既然你似乎也想防止对参数值的空白,你也可以做到使用参数值的空安全的装饰StringUtils.trimToEmpty阿帕奇共享郎

String action = StringUtils.trimToEmpty(request.getParameter("action"));

System.out.println("Action: " + action);

if("something".equals(action)) {
   System.out.println("hey");            
}

回答by user486760

try this :

试试这个 :

String action = request.getParameter("action");
System.out.println("Action: " + action);

if(action.trim().equals("something"))
{
    System.out.println("hey");            
}

回答by dpq

Just a wild guess: could be that one of these "somethings" contains e.g. a Cyrillic character that looks identical to its Latin counterpart. In this case, it could be the "o".

只是一个疯狂的猜测:可能是这些“东西”中的一个包含例如看起来与其拉丁对应物相同的西里尔字符。在这种情况下,它可能是“o”。

回答by Frank

The equals method compares the strings for object identity and compares not the content. To compare the content of two strings, use the compareTo method.

equals 方法比较对象标识的字符串,而不比较内容。要比较两个字符串的内容,请使用 compareTo 方法。