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.
You’re using
||when you should be using&&: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: