Homework 11
1.
StringVector
class (10 points)Create a class called
StringVector
, which is a child of theVector
class (defined by Java). The new class definiton should include the following:
- a default constructor, which calls the default constructor of the parent
Vector
class.- a public method called
getElementAt(int index)
, which returns theString
object stored at the specifiedindex
in the vector.- a public method called
getFirstElement()
, which returns theString
object stored at index 0 in the vector.- a public method called
getLastElement()
, which returns theString
object stored at the last occupied index in the vector.- a public method called
toStringArray()
, which returns the contents of the vector as an array ofString
objects (order is preserved).HINT: The first three methods should be implemented in one line, while the
toStringArray()
method will require a little more work. Utililize the methods inherited from theVector
class to make your job easier. Also, casting an object of typeObject
to an object of typeString
will be needed.Important Notes:
- the line
import java.util.Vector;
must appear at the top of theStringVector.java
source code file before anything else!- the documentation for the
Vector
class, defined by Java, can found at: http://java.sun.com/j2se/1.3/docs/api/java/util/Vector.html
2.
StringLister
class (10 points)Write a program that allows the user to enter an arbitrary number of strings (words, sentences, etc.) one line at a time, stores the strings in a single
StringVector
object, and then prints out a list of the strings entered in reverse order. The end of user input should be indicated when the user enters a string of length zero (i.e. just hits the enter key without typing anything in). A sample output might look like:Please enter a word (press 'Enter' to end input): hello Please enter a word (press 'Enter' to end input): this Please enter a word (press 'Enter' to end input): is Please enter a word (press 'Enter' to end input): so Please enter a word (press 'Enter' to end input): cool! Please enter a word (press 'Enter' to end input): cool! so is this hello3.
StringSorter
class [Extra Credit] (10 points)Modify the program in Problem 2 to sort (alphabetical order) the strings stored in the
StringVector
and then print out the elements of the sorted vector in correct order (i.e not reverse order). A sample output might look like:Please enter a word (press 'Enter' to end input): hello Please enter a word (press 'Enter' to end input): this Please enter a word (press 'Enter' to end input): is Please enter a word (press 'Enter' to end input): so Please enter a word (press 'Enter' to end input): cool! Please enter a word (press 'Enter' to end input): cool! hello is so thisHINT: refer to pp. 136-139 of the Savitch text for assistance on sorting strings in alphabetical order.