I got this code:
System.out.println("Enter the brand and cash value");
String brand = keyboard.nextLine();
long cash = keyboard.nextDouble();
String buffer = keyboard.nextLine();
but even though I enter the exact String value I am trying to compare to, it fails to recognize they are the same. Strangely when I enter this:
compare[0] = new Car ("BMW", 12.00);
instead of this:
compare[0] = new Car (brand, 12.00);
it works
I also use equals:
public boolean equals(Car other)
{
if (other == null)
{
return false;
}
if(this.brand == other.brand && this.cash == other.cash)
{
return true;
}
else
{
return false;
}
}
You are using
==to test String equality, and"BMW"is a String literal, which is interned in a pool whereasbrandisn’t. In other words, if you have:s1 == s2is trues1 == s3is falses2 == s3is falses1.equals(s2)is trues1.equals(s3)is trues2.equals(s3)is trueBottom line: you should use
equalsto compare strings.You can read more about it in this post.
EDIT
In the code of your
equalsmethod you need to changeto this:
Also note there are a few other issues with your
equals– in particular, it does not override equals: it should bepublic boolean equals(Object o)EDIT 2
You could implement your equals method like this for example (it assumes that brand can’t be null – if it is not the case you need to handle that specific case too)
Note that you should also override the
hashcodemethod.