ulrail.gif

Homework 2

 

ur-2c.gif

urrail.gif

blrail-nonavbar.gif

Home | Resources | Homeworks | Exams
Lectures | Labs | Contacts | Submit | TAs

br-2a.gif

 

br-2c.gif

brrail.gif

spacer.gif

spacer.gif

Purpose

Computer programs often need to manipulate representations of collections of things. In general, a given program might need to represent several different collections. An example is a payroll program: it needs to represent the set of employees of a company in order to compute and print end-of-month payroll checks (another collection!). Similarly, word processing programs maintain collections of documents; and digital photo editing programs, such as Photoshop and Picasa, manage such things as sets of photographs and for each such photograph a set of layers. (Don’t worry if you don’t know about layers in Photoshop.) The goals of this homework assignment are two-fold:

  1. To expose you to writing computer programs that manipulate abstract representations of collections of objects. In particular, we will introduce you to the Java Vector class.

  2. To reinforce the distinction between classes (such as Vector) and objects (such as two distinct Vector objects, representing two distinct collections).

A Vector represents a mutable ordered collection. By mutable we mean that a program, as it runs, can change the membership of a collection, adding and deleting members. An object of type Vector that represents an empty collection when a program starts running might represent a collection with many members by the time the program terminates. By the term ordered we mean that the members of the collection are arranged in a linear order: the first element (if any) is followed by the second element (if any), and so forth. The Java Vector class defines a set of methods to manipulate Java Vector objects – which is to say, to manipulate abstractions of ordered collections.

There is one file that you have to submit for this homework, called VectorUsage.java. We are not providing you with skeleton code. The VectorUsage class declaration must be public: public class VectorUsage. Remember: capitalization matters. The capital 'V' and 'U' in VectorUsage are significant. Also note that the file name must match the class name -- so the file name must be VectorUsage.java.  If you do not capitalize it as shown, Java will not compile your program properly, and you will have points taken off. All of your code for this assignment must be within the main() method in your VectorUsage class. As the Vector class is defined n the java.util library (along with the Scanner class), you will need to have the following line at the top of your file: import java.util.*;

Background

The Vector class defines methods for (among other things) adding and remove "things" from Vector objects. Creating several Vector objects lets a program maintain several different collections. For this homework, we will be creating String objects (i.e., objects of type String), and storing them in one of two Vector objects (objects of class Vector). Think of each Vector object as being like a different container (such as a backpack) : you can insert (add) items into it, remove items from it, count how many items are in it, etc. Different Vectors (like different backpacks) can contain different collections of things.

Elements inserted into a Vector have an index value, in the same way that the characters in a String have an index (first, second, third, etc). The first element has index 0, then 1, etc.

The following code illustrates the use of a Vector.

Vector v = new Vector();         // Creates a new Vector object v
v.add ("first string");          // Adds "first string" as the first element in 
                                 // the vector (it has index 0)
v.add ("second string");         // Adds "second string" as the second element in 
                                 // the vector (it has index 1)
                                 // At this point, the Vector contains two elements
System.out.println (v.size());   // Prints the size (2) to the screen
System.out.println (v);          // Prints the entire Vector (meaning each element) 
                                 // to the screen
String s = (String) v.get(0);    // Gets the first element from the Vector
v.remove (0);                    // Removes the first element (the one at position 0)
                                 // At this point, the Vector contains one element:
                                 // "second string"

A few things to notice in this code segment:

  • To print the Vector to the screen, you just put the Vector into a System.out.println() statement, as shown on the 8th line. Later in the semester we will see why Java allows us to do this.

  • When you are retrieving an element from the Vector, you need to cast it into a String, as shown on the 10th line. We will see why this is necessary at the very end of the course.

Compiler Warnings

When you compile your program for HW J2 (and the above code), you will receive the following warning:

Note: VectorUsage.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

This is a warning, not an error message. In general, it’s very important that programmers not ignore such warning messages. They sometimes constitute evidence of problems with your code. For this homework assignment, however, you can ignore it. This particular warning is due to how the Vector class was written by the designers of Java.  Your program will still have compiled properly (assuming there were no other error messages).

Vector Methods

The following are the methods defined in the Vector class (and thus applicable to Vector objects) that you will be using for this homework.

  • Vector (): The constructor, it creates a new Vector object.

  • add (Object o): Adds the passed object to the Vector in the next available spot.

  • int indexOf (Object which): Searches the Vector to find the position where the passed object is. Returns -1 if the element is not found.

  • Object firstElement (): Returns the first element of the Vector.

  • Object lastElement (): Returns the last element of the Vector.

  • Object get (int which): Returns the element at the passed position

  • Object remove (int which): Removes the element at the passed position

  • set (int index, Object element): Sets the element at position index to the passed element.

  • clear (): Clears the Vector (removes all elements from it)

  • int size (): Returns the size of the Vector.

As mentioned above, any time you obtain an element from the Vector (via firstElement(), lastElement(), get(), or remove()), you need to cast the returned element back as a String, as shown below.

String s = (String) v.get(0);

Lastly, you will notice that the methods are defined take in and return values of type Object, not String. For this homework, you can ignore the distinction between Object and String by treating them as if they are the same thing. (There are complications here that we’re not yet prepared to explain or understand, so we’ll just gloss over them for now.)

Design

Your code must perform the following steps.  While there are a lot of steps, many of them are repeated (such as steps 2, 5, 10, and 15).  Note that some of the steps are colored.  The blue steps are those that print out both Vectors, along with the sizes -- as mentioned just before, all these steps are the same.  Note that there are still other steps that require output (such as 13).  The green steps are the steps that require user input.

  1. Create two new Vector objects, stored in separate variables

  2. Print out each Vectors’ size, and all of the elements that they contain (using a single System.out.println() statement for each Vector – see above)

  3. Read in 4 Strings from the keyboard, one at a time, and insert each of them into the first Vector object.  Use the next() method from Scanner, NOT nextLine().

  4. Read in 4 additional strings from the keyboard, one at a time, and insert each of them into the second Vector object.  Use the next() method from Scanner, NOT nextLine().

  5. Print out each Vectors’ size, and all of the elements that they contain (using a single System.out.println() statement for each Vector – see above)

  6. Get an int i from the keyboard

  7. Print out the element at index i in each of the two vectors

  8. Remove the element at index i in each of the two vectors, and print out that you are doing so.

  9. Insert the first element of the first Vector object to the second Vector object, and print out that you are doing so. 

  10. Print out each Vectors’ size, and all of the elements that they contain (using a single System.out.println() statement for each Vector – see above)

  11. Get another String from the keyboard.  Use the next() method from Scanner, NOT nextLine().

  12. Search the first Vector for that String, and print out the result of that search (this uses the indexOf() method)

  13. Print the first and last elements of Vector 1

  14. Clear the second Vector (remove all elements) (and print that you are doing so)

  15. Print out each Vectors’ size, and all of the elements that they contain (using a single System.out.println() statement for each Vector – see above)

VERY IMPORTANT:  Your code MUST take in the input in the order specified (4 Strings, 4 more Strings, an int, and a String).  This is in steps 3, 4, 6, and 11.  If your code does not take in the input in that order, you will receive points off.  Make sure your program asks for each value it’s going to obtain as input (and only these!). Your program can assume that the int values entered will be valid (i.e. that they won't be negative or larger than the size of the Vector).

As the course progresses, we will provide you with less step-by-step instructions for the homeworks -- for example, we don't specify that you need to create a Scanner object to obtain the input (this should be obvious from the fact that you need to get user input), or that you need to print out a legend (which is included in the good programming practices, below).

The easiest way is to progress through the steps above, in order, is to use incremental development. Start with the Java program that does nothing. Make sure it runs properly. Then add one or two steps worth of code at a time, and test them to make sure they work. Move ahead only when you have justifiable confidence that your program so far is right. Doing a simple test or two is easy (although comprehensive program testing is very hard in the general case): just run your program and see if it works properly up to that point. The steps where you print out the Vectors allow you to see “what's going on”, i.e., to see the current states of the vector objects, and to see how the just-executed statements changed their states. Although there are many steps, each step is relatively small, and most will only take a few lines of code.

Scanner warning

The Scanner class sometimes acts a bit finicky, and this homework may encounter some strange behavior. To avoid any problems, use next() (instead of nextLine()) to read in a String. We won't be testing your code with Strings that contain spaces, so you don't need to either. This should allow you to avoid any of these issues.  However, since you are using next(), you should not put any spaces in your Strings (we won't do so when we test your homework).

Note: You should only create ONE Scanner object in your code -- creating more than one will cause your program to not work properly with the grading routines, which will cause a loss of points.

Good programming practices

The good programming practices listed in HW 1 must be included in this (and all) homeworks.

Sample execution

Note that we label each step to help you understand what is going on -- you don't need to do so (although you may want to do so to help you make sure you got all the steps).  All text in red is what was input by the user.  We will not be testing your program with strings that contain spaces -- you should do the same (i.e. not use spaces in your strings).

Welcome to the Vector Manipulation Program!

Creating new Vectors (step 1)

Vector 1 is size 0 and contains: [] (step 2)
Vector 2 is size 0 and contains: [] (step 2)

Please enter 4 strings: (step 3)
kiwi
lime
pear
orange

Please enter 4 more strings: (step 4)
mango
pineapple
grape
banana

Vector 1 is size 4 and contains: [kiwi, lime, pear, orange] (step 5)
Vector 2 is size 4 and contains: [mango, pineapple, grape, banana] (step 5)

Please enter an integer: (step 6)
3

Element at index 3 in Vector 1 is: orange (step 7)
Element at index 3 in Vector 2 is: banana (step 7)
Removing the element at index 3 of both vectors (step 8)
Adding first element of Vector 1 to Vector 2. (step 9)

Vector 1 is size 3 and contains: [kiwi, lime, pear] (step 10)
Vector 2 is size 4 and contains: [mango, pineapple, grape, kiwi] (step 10)

Please enter another String: (step 11)
pear

Search Vector 1 for pear returned: 2 (step 12)
The first element of Vector 1 is: kiwi (step 13)
The last element of Vector 1 is: pear (step 13)
Cleared Vector 2 (step 14)

Vector 1 is size 3 and contains: [kiwi, lime, pear] (step 15)
Vector 2 is size 0 and contains: [] (step 15)

All done!

Submission

When you are finished, submit the VectorUsage.java file.

 

spacer.gif

spacer.giffooter-middle.gifspacer.gif