比较字符串与字符串值
可能的重复:
Java String.equals 与 ==
我有一个名为 DomainType
的字符串它通常包含来自 url 的“edu,com,org..etc”等值。我使用 if else 语句来帮助检查数据类型并输出 JOptionPane
。由于某种原因,每当您键入任何域类型时,它都会为您提供最后一个选项。
这是我编写的代码的片段:
DomainType = URL.substring(URLlength - 3, URLlength);
if (DomainType == "gov") {
JOptionPane.showMessageDialog(null, "This is a Government web address.");
}
else if (DomainType == "edu") {
JOptionPane.showMessageDialog(null, "This is a University web address.");
}
else if (DomainType == "com") {
JOptionPane.showMessageDialog(null, "This is a Business web address.");
}
else if (DomainType == "org") {
JOptionPane.showMessageDialog(null, "This is a Organization web address");
}
else {
JOptionPane.showMessageDialog(null, "This is an unknown web address type.");
}
因此 DomainType
给我 edu 或 com 没有问题,但我认为这是我的 if 语句我做得不对。
Possible Duplicate:
Java String.equals versus ==
I have a string called DomainType
which usually holds values like "edu,com,org..etc" from a url. I used an if else statement to help check the data type and output a JOptionPane
. For some reason whenever you type any domain type, It gives you the last option.
Here is a Snippet from the code I wrote:
DomainType = URL.substring(URLlength - 3, URLlength);
if (DomainType == "gov") {
JOptionPane.showMessageDialog(null, "This is a Government web address.");
}
else if (DomainType == "edu") {
JOptionPane.showMessageDialog(null, "This is a University web address.");
}
else if (DomainType == "com") {
JOptionPane.showMessageDialog(null, "This is a Business web address.");
}
else if (DomainType == "org") {
JOptionPane.showMessageDialog(null, "This is a Organization web address");
}
else {
JOptionPane.showMessageDialog(null, "This is an unknown web address type.");
}
so the DomainType
gives me edu or com no problem but i think it's my if statement I'm not doing right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
比较字符串时,切勿使用
==
,而使用equals
。那么,而不是使用
为什么?
==
将比较引用。这意味着:记忆值。对于你的琴弦来说,它们可能不相等。equals
将比较值,这就是您想要的。When comparing strings, never use
==
, useequals
. So, instead ofuse
Why?
==
will compare references. That means: memory values. And they may not be equal for your strings.equals
will compare values, and that is what you want.要比较内容,请使用
equals
,而不是==
(比较引用):To compare content use
equals
, not==
(which compares references):顺便说一句,大型如果可能不是最优雅的方式 - http://www.antiifcampaign。 com/ - 抱歉,只是迂腐。
.equals() 方法确实是比较对象的正确方法。
On a side note, a mega-if is probably not the most elegant way to do that - http://www.antiifcampaign.com/ - sorry, just being pedantic.
The .equals() method is the right way to compare objects indeed.