2012-11-24 44 views
0

我得到这个代码:输入从nextLine阅读不等于字符串值

System.out.println("Enter the brand and cash value"); 

    String brand = keyboard.nextLine(); 

    long cash = keyboard.nextDouble(); 
    String buffer = keyboard.nextLine(); 

,但即使我进入我想比较确切的字符串值,它没有认识到它们是相同的。奇怪的是,当我进入这个:

compare[0] = new Car ("BMW", 12.00);

,而不是这样的:

compare[0] = new Car (brand, 12.00);

它的工作原理

我也用等于:

public boolean equals(Car other) 
{ 
    if (other == null) 
    { 
     return false; 
    } 

    if(this.brand == other.brand && this.cash == other.cash) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 
+2

您是否使用.equals()方法检查相等性? ==在这里不起作用 –

+0

在进行比较之前,打印出您正在比较的两个字符串。这应该可以帮助您查看是否有任何差异。另外,不要使用'=='来比较字符串(如前所述)。 –

+0

我使用等于我重新定义了它 –

回答

2

您正在使用==至测试字符串相等,而"BMW"是一个字符串字面值,它在一个池中被执行,而brand不是。换句话说,如果您有:

String s1 = "BMW"; 
String s2 = "BMW"; 
String s3 = getString(); //receives "BMW" from the scanner 

s1 == s2是真的
s1 == s3是假
s2 == s3是假
s1.equals(s2)是真的
s1.equals(s3)是真的
s2.equals(s3)是真的

底线:您应该使用equals来比较字符串。

你可以在this post了解更多关于它的信息。

编辑

在你equals方法,你需要改变

if(this.brand == other.brand && this.cash == other.cash) 

此代码:

if(this.brand.equals(other.brand) && this.cash == other.cash) 

还要注意有一些其他问题,您equals - 特别是,它不会覆盖等于:它应该是public boolean equals(Object o)

EDIT 2

你可以实现你的equals方法是这样的例子(它假设品牌不能为空 - 如果没有你需要处理特定情况下也如此)

@Override 
public boolean equals(Object obj) { 
    if (obj == null || getClass() != obj.getClass()) { 
     return false; 
    } 

    final Car other = (Car) obj; 
    return (this.cash == other.cash && this.brand.equals(other.brand)); 
} 

请注意,您还应该覆盖hashcode方法。正如我在下面所示

public boolean equals(Car other) 
{ 
    if (other == null) 
    { 
     return false; 
    } 

    if(this.brand.equals(other.brand) && this.cash.equals(other.cash)) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 
+0

我使用equals()这可能不是问题 –

+0

@GladstoneAsder我知道你在你的Book类中覆盖了'equals'。你可以显示该代码吗?我可以想象,在“equals”方法中,您将品牌与“if(this.brand == other.brand){}'进行比较。 – assylias

+0

我真的不知道什么是错的 –

0

使用java.lang.Object的平等法==用于检查r字符串的参考及其值。

在这种情况下,您的值是相同的,但不是参考。

因此,您需要使用equals,因为它仅用于检查值。
这就是你想要做的,我猜。

+1

this.cash.equals(other.cash)在这里是错误的。 – vels4j

+0

它工作,即使我把等于现金 –

+0

@ vels4j这取决于如果现金是一个'双'或'双'。它似乎是一个“双”,但在这种情况下,“等于”东西不会真正编译。 – assylias

1

您需要使用

this.brand.equals(other.brand)

if条款,而不是

this.brand == other.brand 

的的