27.0k views
3 votes
Exercise 7.1.7: Car Inventory Spoints Let's Go A car company wants to keep a list of all the cars that they have in stock. The company has created a Car class that stores important information about each of their cars. Initialize an ArrayList called inventory that stores each Car that the company has in stock. Status: Not Submitted 7.1.7: Car Inventory Save Submit + Continue iii FILES о со Ол еш мн import java.util.ArrayList; 2 public class CarTracker 3- { public static void main(String[] args) 5 { 6 //Initialize your ArrayList here: 7 } CarTracker.java Car.java Status: Not Submitted 7.17: Car Inventory Save Submit + Continue !!! 2-{ FILES 1 public class Car 3 String name; String model; 5 int cost; public Car (String name, String model, int cost) { this.name 10 this.model = model; this.cost = cost; 12 } CarTracker.java Car.java 6 7 8- 9 = name; 11 13

User Argoneus
by
5.8k points

1 Answer

6 votes

Answer: To initialize an ArrayList called inventory that stores Car objects in Java, you can use the following code:

import java.util.ArrayList;

public class CarTracker

{

public static void main(String[] args)

{

// Initialize your ArrayList here:

ArrayList<Car> inventory = new ArrayList<>();

}

}

The ArrayList is initialized using the ArrayList<Car> syntax, where Car is the type of objects that will be stored in the ArrayList. The ArrayList is then instantiated using the new ArrayList<>() syntax. You can then add Car objects to the ArrayList using the add method. For example, the following code adds a Car object with the name "Ford", model "Fiesta", and cost $15,000 to the inventory ArrayList:

// Add a Car object to the inventory ArrayList

Car car1 = new Car("Ford", "Fiesta", 15000);

inventory.add(car1);

You can add as many Car objects to the inventory ArrayList as you need. To retrieve a Car object from the ArrayList, you can use the get method and specify the index of the Car object you want to retrieve. For example, the following code retrieves the first Car object in the inventory ArrayList:

// Get the first Car object in the inventory ArrayList

Car car = inventory.get(0);

You can then access the fields of the Car object using the dot notation, as shown in the following code:

// Print the name, model, and cost of the Car object

System.out.println("Name: " + car.name);

System.out.println("Model: " + car.model);

System.out.println("Cost: $" + car.cost);

This code would output the name, model, and cost of the Car object.

User Ayush Bansal
by
5.7k points