将字符串与字符串值进行比较

时间:2011-10-01 14:17:24

标签: java string if-statement

  

可能重复:
  Java String.equals versus ==

我有一个名为DomainType的字符串,它通常包含来自网址的“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声明我做得不对。

3 个答案:

答案 0 :(得分:4)

比较字符串时,请勿使用==,请使用equals。所以,而不是

DomainType == "org"

使用

DomainType.equals("org")

为什么呢? ==将比较参考文献。这意味着:内存值。他们的字符串可能不一样。 equals会比较值,这就是你想要的。

答案 1 :(得分:1)

要比较内容使用equals,而不是==(比较引用):

if (DomainType.equals("gov")) {

答案 2 :(得分:0)

另一方面,mega-if可能不是最优雅的方式 - http://www.antiifcampaign.com/ - 抱歉,只是迂腐。

.equals()方法确实是比较对象的正确方法。

相关问题