CS 121: Assignment 2
Review of CS 120
Due: Tuesday, January 22, 10:00 am
Write a program that can create random English sentences consisting out of a subject, verb, object, and an adverbial.
The object and the adverbial are optional. Examples of such sentences are:
- "The cat caught the mouse." (subject = "the cat", verb = "caught", object = "the mouse")
- "John lies." (subject = "John", verb = "lies" )
- "John met Mary in the mall."(subject = "John", verb = "met", object ="Mary", adverbial = "in the mall")
Part A. To implement this program, do the following:
- Create an interface SentenceUnit. It has two methods: String toText(),
which returns the contents of the grammatical unit (e.g., "the cat"),
and String toStructure(), which returns the type of the unit followed by the text surrounded
by parentheses (e.g., "subject (the cat)" )
- Create the following classes, which implement SentenceUnit: NounUnit, Verb, Adverbial. Each of these has
a zero-parameter constructor which creates a random text of the appropriate kind. A NounUnit can represent
either a subject or an object.
- The SentenceUnit classes have constant arrays that contain sample strings, e.g. "the cat" for a NounUnit.
Each class should have at least five sample strings.
- Create a Sentence class. It has fields called subject, verb, object, and adverbial; only object and adverbial
may be null. Its constructor creates a random sentence by assigning newly created SentenceUnits to the
fields. There are appropriate getter methods for all fields. Class Sentence also implements SentenceUnit.
- Create a main method that creates a new random Sentence and prints it out, both as plain text (using toText()), and showing its structure
(using toStructure()).
Part B. Extend the program as follows:
- Create a subclass of Adverbial called AdverbialClause. It represents an adverbial clause such as "when they left" or
"where the birds fly" or "how they liked it". Implement AdverbialClause by generating a question word (such as
"how", "where") followed by a Sentence.
- Update class Sentence so that there is a 50% chance a sentence has an adverbial, and if it has an adverbial, there
is a 50% chance that it is an adverbial clause.
- Create a subclass of NounUnit called NounClause. It starts with "that" and a Sentence follows, for example:
"that John likes Mary". A NounUnit has a 1/3 chance of being a NounClause.
- Update the main method to print out 20 random sentences.
- Note that it can occur that clauses are nested,
i.e., a NounClause could contain an AdverbialClause.
Use proper class design throughout, an use documentation comments for all classes, interfaces, methods, constructors, and fields.
CS 121