MJ93
MJ93

Reputation: 5296

My method won't let me leave a for loop while going through an array

I have a method which adds a new vehicle(Honda) to the vehicles array. The array contains a maximum of 4 vehicles.

Vehicle[] vehicles = new Vehicle[4];

The method is supposed to add 1 new Vehicle object to the end of the vehicles array if there is a null value. The problem is that it is writing to ALL of the null values in the array instead of just writing to 1 and then kicking out of the for loop.

Here is what I have (NOTE -- I am required to use an array instead of ArrayList):

public void addVehicle(Vehicle Honda[]) throws FileNotFoundException
{
    boolean found = false;
    if(canAddVehicle() == true)
    {
        for(int i = 0; i < vehicles.length || !found; i++)
        {
            if(vehicles[i] == null)
            {
                Scanner reader = new Scanner(file);
                Honda[i] = new Vehicle();
                Honda[i].readRecord(reader);
                vehicles[i] = Honda[i];
                reader.close();
                found = true;
            }

        }
        System.out.println("Vehicle Added!");

    }
}

I've set found = true to make sure it leaves the for loop as soon as it finds the first null value in the array.. but it doesn't seem to be working. Why would this be?

EDIT: Also, I am not allowed to have any other class level data.

Upvotes: 2

Views: 107

Answers (2)

Paul Bellora
Paul Bellora

Reputation: 55223

You're using || when you should be using &&:

for(int i = 0; i < vehicles.length && !found; i++)

More information on the conditional operators can be found in this Java Tutorials article.

As a friendly critique, this isn't very readable to another developer. The following would be easier to follow:

for(int i = 0; i < vehicles.length; i++)
{
    if(vehicles[i] == null)
    {
        Scanner reader = new Scanner(file);
        Honda[i] = new Vehicle();
        Honda[i].readRecord(reader);
        vehicles[i] = Honda[i];
        reader.close();
        break; //break out of the loop
    }
}

Upvotes: 7

Austin Heerwagen
Austin Heerwagen

Reputation: 663

Instead of for(int i = 0; i < vehicles.length || !found; i++) use for(int i = 0; i < vehicles.length && !found; i++)

Replace the or operator || with the and operator &&. Basically it was seeing that found was true, but i was still less than vehicles.length so the loop continued. With && both need to be true in order for it to run.

Upvotes: 1

Related Questions