I stuck with the logic and need help for my project.
I have a text file with 5 vehicle names in it.
Then I have to read them into an ArrayList, which I did using:
public static void main(String[] args) throws IOException
{
BufferedReader bTextFileVehicleNames = new BufferedReader(new FileReader("vehicles.txt"));
ArrayList<String> vechicleNamesArray = new ArrayList<String>();
while((textFileLine = bTextFileVehicleNames.readLine()) != null)
{
vehicleNamesArray.add(textFileLine);
}
Now, I need to create an object for every item (vehicle name) in the ArrayList, which I did using:
for(String s : vehicleNamesArray)
{
newVehicle = new Vehicle(s);
//I defined this Vehicle newVehicle = null; in the main class. My main is also in the same Vehicle.java file.
}
Each of these objects have attributes: power, angle, speed;
and behaviours: powerOn(), powerOff(), SpeedUp(), SlowDown(), etc.. which I defined in Vehicle class.
Now, the user has to enter Vehicle name command. Then I split them and took [0], which is the vehicle name, and have to first check if it is one of those vehicle names in the ArrayList (derived from txt file), and if it is then have to refer it to that particular object I created above. And then have to take in the [1], which is command that corresponds to the particular behaviour of object, which can be powerOn, speedUp, etc etc..
for (int i=0; i< vehicleNamesArray.size(); i++)
{
if (vehicleNamesArray.get(i).matches(userVehicleName))
//userVehicleName is the [0] vehicle name entered by user
//userVehicleCommand is the [1] command entered by user
{
switch (userVehicleCommand.toLowerCase())
{
case "power on":
newVehicle.powerOn(); //calling that particular bahaviour of the object defined in Vehicle class.
System.out.println(newVehicle.getName()+" is powered ON.");
break;
...
...
For example, let's consider there are 5 vehicles in the txt (thereby in the ArrayList) named: Audi, Bmw, Mercedez, Volkswagen, Porsche.
The problem is that whatever I enter in the vehicle name command, the program by default is taking the last element, in this case Porsche in the ArrayList.
I.e., when I say "Audi, powerON", it still prints out "Porsche is powered ON."
I think I messed up in linking the user entered name to check with the ArrayList and then refering it to that particular object.
newVehicleobject and you assign each item to it. At the end, the last assignment is what's left. Also, you should use atry-with-resourcesblock to close yourBufferedReader.newVehiclevariable is one variable holding one vehicle instance, thus if you assign it a value in a loop, it will retain the last one. If you want to have a list of vehicles, well, you have to create and populate a list.switchblock instead ofnewVehicle.getName()you have to usevehicleNamesArray.get(i).getName()oruserVehicleName