ulrail.gif

Homework J2

  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. A boring 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 Picassa, 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. The first goal is to exposure you to writing computer programs that manipulate abstract representations of collections of objects. In particular, we will introduce you to the Java Vector class. The second goal is 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 type 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 define 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, 13, 16, 18, and 20).

  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 5 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 5 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 another String from the keyboard.  Use the next() method from Scanner, NOT nextLine().
  7. Search the first Vector for that String, and print out the result of that search (this uses the indexOf() method)
  8. Search the second Vector for that same String, and print out the result of that search (this uses the indexOf() method)
  9. Print the first and last elements of the first and second Vector, respectively
  10. Get an int i from the keyboard
  11. Print out the element at position i in each of the two vectors
  12. Remove the element at position i in each of the two vectors, and print out that you are doing so.
  13. 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)
  14. Get a String s and an int i from the keyboard.  Use the next() method from Scanner, NOT nextLine().
  15. Set the element in the first Vector at position i to the String s (and print that you are doing so)
  16. 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)
  17. Clear the first Vector (remove all elements) (and print that you are doing so)
  18. 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)
  19. Clear the second Vector (remove all elements) (and print that you are doing so)
  20. 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)
  21. Terminate

VERY IMPORTANT:  Your code MUST take in the input in the order specified (5 Strings, 5 more Strings, yet another String, an int, a String, and an int).  This is in steps 3, 4, 6, 10, and 14.  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 this. 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).

Good programming practices

The good programming practices listed in HW J1 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 has size: 0, and has elements: [] (step 2)
Vector 2 has size: 0, and has elements: [] (step 2)
Please enter 5 strings to insert for the first vector (step 3)
alpha
beta
gamma
delta
epsilon
Please enter 5 strings to insert for the second vector (step 4)
first
second
third
fourth
fifth
Vector 1 has size: 5, and has elements: [alpha, beta, gamma, delta, epsilon] (step 5)
Vector 2 has size: 5, and has elements: [first, second, third, fourth, fifth] (step 5)
Please enter another string to search the Vectors for (step 6)
gamma
Search Vector 1 for gamma returned: 2 (step 7)
Search Vector 2 for gamma returned: -1 (step 8)
First element of Vector 1: alpha (step 9)
Last element of Vector 2: fifth (step 9)
Please enter an int i -- to print and the remove that element in the Vectors (step 10):
2
Element 2 in vector 1 is gamma (step 11)
Element 2 in vector 2 is third (step 11)
Removing element at position 2 from both vectors (step 12)
Vector 1 has size: 4, and has elements: [alpha, beta, delta, epsilon] (step 13)
Vector 2 has size: 4, and has elements: [first, second, fourth, fifth] (step 13)
Please enter another string to put in the vector (step 14)
omega
Please enter a integer -- the position to stick that element (step 14)
2
Setting element 2 in vector 1 to omega (step 15)
Vector 1 has size: 4, and has elements: [alpha, beta, omega, epsilon] (step 16)
Vector 2 has size: 4, and has elements: [first, second, fourth, fifth] (step 16)
Clearing Vector 1 (step 17)
Vector 1 has size: 0, and has elements: [] (step 18)
Vector 2 has size: 4, and has elements: [first, second, fourth, fifth] (step 18)
Clearing Vector 2 (step 19)
Vector 1 has size: 0, and has elements: [] (step 20)
Vector 2 has size: 0, and has elements: [] (step 20)
All done! (step 21)

Submission

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

spacer.gif
spacer.giffooter-middle.gifspacer.gif