我得到了这个代码:
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);
而不是这个:
比较[0] = 新车(品牌,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;
}
}
最佳答案
您正在使用 ==
来测试字符串相等性,并且 "BMW"
是一个字符串文字,它被保留在池中,而 brand
> 不是。换句话说,如果您有:
String s1 = "BMW";
String s2 = "BMW";
String s3 = getString(); //receives "BMW" from the scanner
s1 == s2
为 true
s1 == s3
为 false
s2 == s3
为 false
s1.equals(s2)
为 true
s1.equals(s3)
为 true
s2.equals(s3)
为 true
底线:您应该使用 equals
来比较字符串。
您可以在this post中阅读更多相关信息。 .
编辑
在您的 equals
方法的代码中,您需要更改
if(this.brand == other.brand && this.cash == other.cash)
对此:
if(this.brand.equals(other.brand) && this.cash == other.cash)
另请注意,您的 equals
还存在一些其他问题 - 特别是,它不会覆盖 equals:它应该是 public boolean equals(Object o)
编辑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
方法。
关于java - 从 nextLine 读取的输入不等于字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13539152/