CS111

Lab 10

Wed April 4, 2012

Custom-made Java Objects cartoon mom and kid in car


The goal of this lab is to give you practice with:

In particular, we will define a class named Vehicle to represent information about vehicles. There are no code files to download; you will be writing all your java code today from scratch.

Part I: Vehicle class

We will define a Java class, named Vehicle, that will allow us to store information about a single vehicle. For this application, we are interested in the following information, related to a vehicle instance:
  1. the type of the vehicle: SUV, minivan or utility car
  2. the number of passengers the vehicle can fit (ranges from 1-10)
  3. the color of the car

Instance Variables

What instance variables do we need to have in the Vehicle class? Make all your instance variable private and of type String.

Constructor

The job of a constructor is to give initial values to the instance variables of a class. Here is an example of how this constructor will be called:

Vehicle v1 = new Vehicle("minivan", "10", "red");

Testing your code: main()

Add a main() method to your Vehicle.java file, so you can test your code as you develop it. As always, you should test your code incrementally, as you add it to the Vehicle.java file.

You can test your code by creating vehicles within your main method, e.g.

Vehicle bigCar = new Vehicle("minivan", "10", "white"); 
You should test the constructor by creating a couple of vehicle instances.

Instance Methods

In your main() method, test the methods you have defined so far on a couple of instances of the Vehicle class.

Part II: VehiclesCollection class

In order to write the code for this part, you'll need to download the lab10_programs folder in the cs111 download directory. The purpose of this class is to keep track of a collection of objects of type Vehicle.

Instance Variables

In this implementation we will use a list to hold the Vehicle instances. In particular, we will use the ObjectList implementation of a list. Add the following two instance variables to your class:

  ObjectList collection; //linked list to hold the Vehicle instances
  int size; //number of Vehicles in the list, at any point
  

Constructor

The constructor creates the instance variable object list, collection, initially to be empty. Then, it fills it in by reading data from a file, named vehicles.txt. This text file contains data about a few Vehicles, one piece of datum per line. Here is how you can read from this file, line by line, create Vehicle instances and add them to the collection:

Scanner scan = new Scanner(new File("vehicles.txt"));
   while (scan.hasNext()) {
     String type = scan.nextLine();
     String passengers = scan.nextLine();
     String color = scan.nextLine();
     Vehicle v = new Vehicle(type, passengers, color);
     collection = ObjectList.prepend(v, collection);
     size++;
   }
   scan.close();


Other methods to define