2

I'm trying to display Car from fleet ArrayList using user input. Unfortunately I'm not sure how to go about it. I have found few examples online but cannot make them work. I have incorporated following method:

 void findRegNo(String reg){
     boolean exist=false;
        for(int i=0;i<this.fleet.size();i++){
            if(this.fleet.get(i).getRegNo() == reg){
                exist=true;
                break;
            }
        }

        if(exist) {
            System.out.println("!!!!!");
        } else {
            System.out.println("xxx");
        }    
}

At the moment the result is always: xxx so the code does not find any match. That function is placed in my container class, I was thinking that maybe it supposed to be in different location. These are variables of Car class:

public class Car {

    //defining variables
    String regNo;
    String model;
    double mileage;
1
  • 2
    Use String.equals to compare strings Commented Apr 26, 2015 at 21:15

1 Answer 1

2

Strings are objects, not primitives. Hence, you should use equals to compare their value, not ==, which checks that both references are to the same object:

if (this.fleet.get(i).getRegNo().equals(reg)) {
    exist = true;
    break;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that, was struggling for a bit with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.