为什么我的字符串比较不起作用? [英] Why doesn't my string comparison work?

查看:108
本文介绍了为什么我的字符串比较不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这是愚蠢的,但wtf正在进行?

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

我在servlet中有一个String变量,它取一个参数的值并基于该值值我做了一些测试,但如果不起作用。有什么问题?

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 if is not working. What is the problem?

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

在控制台上,System.out.println显示了我的值行动是某事

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

Action: something


推荐答案

你的第二次比较是错误的。您还应该使用等于而不是 == ,如下所示:

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

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

== 运算符比较(String)对象的引用,在正常情况下相等字符串不会自动具有相同的引用,即它们是不同的对象。 (除非两者都内化,但通常你不应该考虑它)

The == operator compares references of (String) objects and under normal circumstances equal strings 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:将文字字符串与动态字符串对象进行比较时,最好调用 equals 方法:

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

"something".equals(action)

这样,当字符串对象为空时,可以避免NullPointerExceptions。

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

这篇关于为什么我的字符串比较不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆