CPSC 124 Introduction to Programming Spring 2008

Lab 10 Solutions

Answers to the exercises are in bold.
  1. Modify the file DMV.java (in the lab10 directory) to extend the Vehicle class. You should create three new classes that extend vehicle: Car, Truck, and Motorcycle. The Car class should contain a variable that indicates the number of doors, the Truck class should contain a variable that contains the number of axels, and the motorcycle should contain a boolean that indicates whether it has a sidecar. You should also write a constructor for each class, which uses parameters to set all of the Car, Truck, and Motorcycle variables (including inherited variables). You also must write a print method in each of the three classes (since this method is declared abstract in the Vehicle class) that prints out all the variables in that class, including inherited variables as well as the name and license number of the owner of the vehicle. Finally, in the main() method in the main class DMV, create at least one Car, Truck, and Motorcycle object and print each one of them out. You should also call the method transferOwnership() at least once. You will need to use at least two instances of the Person object to represent the owners of the various vehicles that you create.

    Answer:
    // add Car class...
    /* Class for modeling a car
       Author: Marc Corliss */
    class Car extends Vehicle {
        protected int numberOfDoors;  // number of doors in car
    
        // constructor which sets car fields
        public Car(int r, Person o, int n) {
            // set the three fields (note: two are inherited)
    	registrationNum = r;
    	owner = o;
    	numberOfDoors = n;
        }
    
        // method for printing out car information
        public void print() {
    	System.out.println("Car printout:");
    	System.out.println("  registration number: " + registrationNum);
    	System.out.println("  owner name: " + owner.getName());
    	System.out.println("  owner license number: " + owner.getLicenseNum());
    	System.out.println("  number of doors: " + numberOfDoors);
        }
    }
    
    // add Truck class...
    /* Class for modeling a truck
       Author: Marc Corliss */
    class Truck extends Vehicle {
        protected int numberOfAxels;  // number of axels on truck
    
        // constructor which sets truck fields
        public Truck(int r, Person o, int n) {
            // set the three fields (note: two are inherited)
    	registrationNum = r;
    	owner = o;
    	numberOfAxels = n;
        }
    
        // method for printing out truck information
        public void print() {
    	System.out.println("Truck printout:");
    	System.out.println("  registration number: " + registrationNum);
    	System.out.println("  owner name: " + owner.getName());
    	System.out.println("  owner license number: " + owner.getLicenseNum());
    	System.out.println("  number of axels: " + numberOfAxels);
        }
    }
    
    // add Motorcycle class...
    /* Class for modeling a motorcycle
       Author: Marc Corliss */
    class Motorcycle extends Vehicle {
        protected boolean hasSideCar;  // does motorcycle have side car?
    
        // constructor which sets motorcycle fields
        public Motorcycle(int r, Person o, boolean h) {
            // set the three fields (note: two are inherited)
    	registrationNum = r;
    	owner = o;
    	hasSideCar = h;
        }
    
        // method for printing out truck information
        public void print() {
    	System.out.println("Motorcycle printout:");
    	System.out.println("  registration number: " + registrationNum);
    	System.out.println("  owner name: " + owner.getName());
    	System.out.println("  owner license number: " + owner.getLicenseNum());
    	System.out.println("  has side car: " + hasSideCar);
        }
    }
    
    /* A database program for the DMV 
       Author: Marc Corliss */
    class DMV {
        /* main method (note: args parameter is unused) */
        public static void main(String[] args) {
            // add code here for creating Cars, Trucks, and Motorcycles
            // and printing them out.  You should build each type of vehicle
            // at least once and call transferOwnership at least once.  In
            // addition, you should create a least two owners (Person objects).
    
            // Add code here...
    
    	// create two people: marc and john
    	Person marc = new Person("Marc Corliss", 1000);
    	Person john = new Person("John Smith", 2000);
    
    	// create a car owned by marc
    	Car c = new Car(4501, marc, 4);
    	// create a truck owned by john
    	Truck t = new Truck(9491, john, 2);
    	// create a motorcycle owned by marc
    	Motorcycle m = new Motorcycle(2521, marc, true);
    
    	// transfer ownership of motorcycle to john
    	m.transferOwnership(john);
    
    	// print out information for car, truck, and motorcycle
    	c.print();
    	t.print();
    	m.print();
        }
    }
    
  2. In this exercise, you will create some classes for representing shapes that can be drawn on a window using Paint.java. In the classes directory, there is a generic class Shape for modeling a generic shape. You will extend this class to create one other shape: a rectangle. You will also extend your rectangle class and a create square class (since a square is just a special kind of rectangle where the width and height are the same). There is also a class Point in your classes directory that extends Shape and models a single point. You should look at both classes before you start writing your own classes.

    There is one big difference between this and previous exercises that involve Paint. Paint can only be used to draw one type of shape, a point. The following would draw a red point at (50, 50):

    Paint.setColor(Color.RED);
    Paint.drawPoint(50, 50);
    

    The methods Paint.drawRect, Paint.fillRect, etc. are not in the version of Paint.java that you will be using in this exercise. If you want to draw a rectangle or a square you will need to do it with multiple calls to Paint.drawPoint (e.g., in some kind of loop).

    The two classes that you must implement are described below:

    Answer:
    /* A class representing a rectangle.  It extends Shape since a rectangle
       is particular kind of shape. 
       Author: Marc Corliss */
    class Rectangle extends Shape {
        /* Width of rectangle */
        protected int width;
        /* Height of rectangle */
        protected int height;
    
        /* Rectangle constructor 
           Takes as parameters the x (int) and y (int) position of the upper, 
           lefthand position of the rectangle, the width (int) and height 
           (int) of the rectangle, and the color of the rectangle. */
        public Rectangle(int x, int y, int width, int height, Color color) {
    	// call Shape's constructor
    	super(x, y, color);
    
    	// initialize width and height
    	this.width = width;
    	this.height = height;
        }
    
        /* Draw the rectangle -- overrides draw() in Shape */
        public void draw() {
    	for (int w = 0; w < width; w++) {
    	    for (int h = 0; h < height; h++) {
    		Paint.setColor(color);
    		Paint.drawPoint(startX+w, startY+h);
    	    }
    	}
        }
    }
    
    /* A class representing a square.  It extends rectangle since a square
       is particular kind of rectangle where the width and height are the same. 
       Author: Marc Corliss */
    class Square extends Rectangle {
        /* Square constructor
           Takes as parameters the x and y position of the upper, lefthand position
           of the square, the width of the square, and the color of the square. */
        public Square(int x, int y, int width, Color color) {
    	// call Rectangle's constructor
    	super(x, y, width, width, color);
        }
    
        // note: don't need to override draw since Rectangle's will work
    }
    
    /* A program that draws several shapes to a window.  
       Author: Marc Corliss */
    class MyPicture {
        /* main method (note: parameter args is unused) */
        public static void main(String[] args) {
            // Several shape variables
            Point p;
            Rectangle r;
            Square s;
    
            // Initialize each shape
    	p = new Point(50, 50, Color.BLUE);
    	r = new Rectangle(100, 100, 125, 200, Color.RED);
    	s = new Square(400, 400, 50, Color.YELLOW);
    
    	// build new window using Paint
    	Paint.buildWindow(/* title */"My Picture", /* starting x */100, /* starting y */100, 
    			  /* horizontal size */500, /* vertical size */500, 
                              /* background color */Color.WHITE);
    
    	// draw shapes
    	p.draw();
    	r.draw();
    	s.draw();
        }
    
    }
    
  3. Finally, write a class MyPicture.java that builds a window and creates some shapes (a point, rectangle, and square) and draws them.

  4. In this exercise, you will write you own Vector class (with less functionality) called NewVector and your own Integer class (with less functionality) called NewInteger. Put all of your classes in a file called PrintReverse.java (you will see why it's called PrintReverse below).

    Your NewVector class should contain the following:

    Your NewInteger class should contain the following:

    Finally, write a class PrintReverse, which contains a main() method. The main() method should read in a sequence of numbers and print them out in reverse using the NewVector and NewInteger classes defined above. First, main() should create a NewVector object for storing the numbers. Then, main() should prompt for and read in numbers until the user enters a negative number. Each number should be used to create a NewInteger object, which is stored on the NewVector object. Finally, the numbers should be removed from the NewVector in reverse order and printed.

  5. For extra credit, add additional methods or constructors from the Vector class to your NewVector class. Look at the online interface for Vector (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Vector.html) to find some methods or constructors. The amount of extra credit will vary greatly with what you decide to implement. More challenging methods and/or constructors will gain you more extra credit points. In addition, the more methods and/or constructors you implement, the more credit you will receive. Put your class in a separate file called ExtraCredit.java (leave your solution from the previous solution intact). Add another class ExtraCredit, which contains a main() method that tests your new Vector functionality. Answer:
    /** Class for representing a vector (replaces Vector)
     *  Author: Marc Corliss
     *  */
    class NewVector {
        /** Array for holding elements (note: partially-full array) */
        private Object[] elements;
        /** Length of elements (needed since array is partially full) */
        private int length;
    
        /** NewVector constructor
         *  Initializes instance variables 
         *  */
        public NewVector() {
    	// give elements a default size of 10, may need to increase size
    	// of array later
    	elements = new Object[10];
    	// at the outset there are 0 elements
    	length = 0;
        }
    
        /** Return number of elements in vector
         *  */
        public int size() {
    	return length;
        }
    
        /** Get element at some position in the vector
         *  Parameter n is the position in vector
         *  Returns element at position n
         *  */
        public Object elementAt(int n) {
    	// check if position is legal, if not, throw exception
    	if (n < 0 || n >= length)
    	    throw new IllegalArgumentException("Vector position " + n + " is out of bounds");
    
    	// otherwise return element
    	return elements[n];
        }
    
        /** Add (insert) an element to the vector at some position
         *  Note: position can be equal to length, i.e., add to end of vector
         *  Parameter n is the position to insert element
         *  Parameter o is the element to insert
         *  */
        public void add(int n, Object o) {
    	// check if position is legal, if not, throw exception
    	if (n < 0 || n > length)
    	    throw new IllegalArgumentException("Vector insertion position " + n + " is out of bounds");
    	
    	// check if array size is large enough, if not, resize
    	if (length >= elements.length) {
    	    // create temporary array to hold elements
    	    Object[] tmp = elements;
    	    // resize array
    	    elements = new Object[elements.length*2];
    	    // copy elements from into newly-sized array
    	    for (int i = 0; i < tmp.length; i++) {
    		elements[i] = tmp[i];
    	    }
    	}
    
    	// insert element into array
    	for (int i = length-1; i > n; i--) {
    	    elements[i] = elements[i-1];
    	}
    	elements[n] = o;
    
    	// increase length of elements
    	length++;
        }
    
        /** Add (insert) an element to end of vector
         *  Parameter o is the element to add
         *  */
        public void add(Object o) {
    	add(length, o);
        }
    
        /** Remove element in the vector at some position
         *  Subsequent elements to the removed element are moved over
         *  Parameter n is the position to remove element
         *  */
        public void remove(int n) {
    	// check if position is legal, if not, throw exception
    	if (n < 0 || n >= length)
    	    throw new IllegalArgumentException("Vector position " + n + " is out of bounds");
    
    	// otherwise remove element from array
    	for (int i = n; i < length-1; i++) {
    	    elements[i] = elements[i+1];
    	}
    
    	// decrement length of elements
    	length--;
        }
    }
    
    /** Class for representing an integer (replaces Integer)
     *  Acts as a wrapper for ints.  Allows ints to be placed in a NewVector.
     *  Author: Marc Corliss
     *  */
    class NewInteger {
        /** Value of integer */
        private int val;
    
        /** NewInteger constructor
         *  Parameter v is the value to set integer to
         *  */
        public NewInteger(int v) {
    	val = v;
        }
    
        /** Getter method for retrieving the int value
         *  */
        public int intValue() {
    	return val;
        }
    }
    
    /** Class for printing inputted numbers in reverse 
     *  Author: Marc Corliss
     *  */
    class PrintReverse {
        /** main method
         *  Parameter args is the command-line arguments (unused)
         *  */
        public static void main(String[] args) {
    	NewVector v = new NewVector(); // holds numbers entered by the user
    	int n = 0;                     // holds the next number entered by the user
    	
    	// prompt user
    	System.out.println("Enter a sequence of integers (<0 to stop):");
    
    	// repeatedly read in ints until input is negative
    	while (n >= 0) {
    	    // get next int
    	    n = TextIO.getlnInt();
    
    	    // if non-negative then add to vector
    	    if (n >= 0) {
    		v.add(new NewInteger(n));
    	    }
    	}
    
    	System.out.println("");
    	System.out.println("The numbers in reverse:");
    
    	// loop over elements in vector
    	for (int i = v.size()-1; i >= 0; i--) {
    	    // get next integer out of vector
    	    NewInteger newInteger = (NewInteger)(v.elementAt(i));
    
    	    // print out int
    	    System.out.println(newInteger.intValue());
    	}
        }
    }