Search code examples
javastring

input read from nextLine is not equal to String value


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;
    }
}

Solution

  • You are using == to test String equality, and "BMW" is a String literal, which is interned in a pool whereas brand isn't. In other words, if you have:

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

    s1 == s2 is true
    s1 == s3 is false
    s2 == s3 is false
    s1.equals(s2) is true
    s1.equals(s3) is true
    s2.equals(s3) is true

    Bottom line: you should use equals to compare strings.

    You can read more about it in this post.

    EDIT

    In the code of your equals method you need to change

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

    to this:

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

    Also note there are a few other issues with your equals - in particular, it does not override equals: it should be public 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)

    @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));
    }
    

    Note that you should also override the hashcode method.