1

I've been learning java for a little over a month with no previous OOP experience, so please provide simple answers!

The project I'm working on is essentially a simple game. I take a txt file with a variable number of vehicle names, and allow a user to enter a vehicle name followed by a command.

How do I create an object for each item in an arraylist?

This is what I have so far (I put an example of what I'm trying to do in code comments):

public class VehicleApp {
public static void main(String[] args) throws FileNotFoundException, IOException{
    File myDir = new File(System.getProperty("user.dir"));
    File myFile = new File(myDir, "vehicleNames.txt");

    FileReader in = new FileReader(myFile);
    BufferedReader br = new BufferedReader(in);

    ArrayList<String> vehicleList = new ArrayList<>();

    int i = 0;
    String line = null;
    while((line = br.readLine()) != null){
        vehicleList.add(line);
        System.out.println(vehicleList.get(i));

        //What I'm essentially trying to accomplish:
        //Vehicle vehicleList.get(i) = new Vehicle();

        i++;
    }

    br.close();


    System.out.println("Enter user input as such:\n" +
            "<vehicle name>, <command>");
}
}

3 Answers 3

3

I presume you want to actually pass the String to the Vehicle class because it is not possible to dynamically assign a variable name:

Vehicle newVehicle = new Vehicle(vehicleList.get(i));

If you actually meant that you wanted to create a new Vehicle for every item in the ArrayList, you can do that as follows:

for(String s : vehicleList){
    Vehicle newVehicle = new Vehicle(s);
}

The above is equivalent to the following:

for(int i=0; i<vehicleList.size(); i++){
    Vehicle newVehicle = new Vehicle(vehicleList.get(i));
}

To identify a Vehicle based on the String passed to it, you should use a getter in the Vehicle class as such:

public class Vehicle {
    private String name;

    public Vehicle(String name){
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Now you can check if a given Vehicle has a name that matches! For example:

Vehicle vehicle = new Vehicle("Honda Civic");
if(vehicle.getName().equals("Honda Civic")){
    System.out.println("Match!");
}
Sign up to request clarification or add additional context in comments.

7 Comments

I'm sure I'm wrong but it looks to me like it only creates 1 object called newVehicle. If I have a method in my class called PowerOn(), how would I call it for lets say a vehicle named fastCar1?
@TryingToCode The first code only creates 1 new Vehicle. But the ones in the for loop create as many Vehicle objects as there are elements in vehicleList
@TryingToCode Ok, if you want to identify a vehicle named "fastCar1", adhering to OOP principles, you should use a getter in the Vehicle class whereby you can verify that the name you gave it is indeed fastCar1.
CanadianDavid, First of all thank your for all your help. I'm afraid I'm still a bit lost here. I'm using your for loop but I'm still not sure how to access the objects I've created. In my vehicle class I have a method called PowerOn() which simply sets a boolean called PowerState to true. So assuming that fastCar1 is an element in the vehicleList, how do I call PowerOn() for the fastCar1 object?
If you need to access the vehicles you created, then you should add them to a List or ArrayList.
|
1

The vehicleList list is of type String. It means that you can only add String objects to that list.

So, you have to change the type of the vehicleList to Vehicle:

ArrayList<Vehicle> vehicleList = new ArrayList<>();

Then, you can create the vehicle objects and pass them in the vehicleList as:

while((line = br.readLine()) != null){
        vehicleList.add(new Vehicle(line));
        System.out.println(vehicleList.get(i).getName());
}

Remember, you must have a constructor that accepts a name, as well as a storage for that name (member field) as:

private String name;    
public Vechicle(String _name)
{
    name = _name;
}

in your Vehicle.java class.

In order to print the name of each Vehicle oject using the System.out.println(vehicleList.get(i).getName());, you have to create a public getter method in your class which retrieves the name of the vehicle:

public String getName()
{
    return name;
}

4 Comments

This looks like it may be what I need. I'm going to play with it, thanks!
I'm not able to print out the name of each vehicle object using your code. I get an error "int cannot be dereferenced".
Yes, you are right, you have to change the System.out.println(vehicleList.get(i.GetName())); to System.out.println(vehicleList.get(i).GetName());
Edit: Ignore last comment. All is well.
1

Okay - first things first. You need a vehicle class. In a file named Vehicle.java (important)

Make a simple class:

public class Vehicle
{
    //vehicle information
    private String name;

    //Constructors
    //default
    public Vehicle()
    {
        name = "";
    }
    //with param
    public Vechicle(String _name)
    {
        name = _name;
    }
}

Now change your array list to contain Vehicle objects

ArrayList<Vehicle> vehicleList = new ArrayList<>();

Then your loop is just

while((line = br.readLine()) != null)
{
        vehicleList.add(new Vehicle(line));
}

That should get you started!

Comments

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.