The problem I’m having is that a Vehicle object is not being deleted from an array (I’m not sure if it’s even storing correctly.)
The user must first add a Vehicle object to the array. And then it brings them back to the menu to ask if they want to add another, or delete an Vehicle.
The method in this class accepts a choice (either 1 or 2) to add a Vehicle to an array, or delete a vehicle from an array:
private void validate(int choice, File file) throws FileNotFoundException
{
Vehicle[] vehicle = new Vehicle[4];
switch(choice)
{
case 1:
store = new Store(file);
store.addVehicle(vehicle);
run();
break;
case 2:
store = new Store();
if(store.deleteVehicle(vehicle) == false)
{
System.out.println("Vehicle not deleted");
}
run();
break;
}
Let’s say the user wants to add a vehicle. It gets passed to the Store class:
My declarations in the Store class:
Vehicle[] vehicles = new Vehicle[4];
The addVehicle method in the Store class:
public void addVehicle(Vehicle vehicle[]) throws FileNotFoundException
{
boolean found = false;
if(canAddVehicle())
{
for(int i = 0; i < vehicles.length || !found; i++)
{
if(vehicles[i] == null)
{
Scanner reader = new Scanner(file);
vehicle[i] = new Vehicle();
vehicle[i].readRecord(reader);
found = true;
reader.close();
}
}
System.out.println("Vehicle Added!");
}
else
{
System.out.println("You can not add more than 4 vehicles.");
}
System.out.println(vehicle[0].getVIN());
}
I added that last line at the bottom to test if it was storing the variables in the Vehicles class from when I called readRecord(). (It shows up correctly.)
Now it will go back to the first method posted and let’s say the user wants to delete a Vehicle. It gets passed to the Store class method (deleteVehicle(vehicle)):
public boolean deleteVehicle(Vehicle vehicle[])
{
System.out.println(vehicle[0].getVIN());
Scanner input = new Scanner(System.in);
String VIN = null;
System.out.println("Please enter the VIN of the vehicle you want to delete:");
VIN = input.next();
for(int i = 0; i < vehicles.length; i++)
{
if(vehicle[i] != null)
{
if(vehicle[i].getVIN().equals(VIN))
{
vehicle[i] = null;
return true;
}
}
}
return false;
}
I added that line at the top to see if there was still a value for the VIN in slot 0 of the vehicles array… it turns out I get a NullPointerException error there… so it seems the first Vehicle object added is not being stored in the array correctly? I’m new to arrays and kind of lost as to what I am doing wrong. Any help would be appreciated. Thanks!
Since you set store to new Store() every time, this is a fresh new instance of the Store class, so there is nothing to be deleted.