Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

n this project, you create a Java application that generates what I am calling p

ID: 3818786 • Letter: N

Question

n this project, you create a Java application that generates what I am calling pseudo-sentences. These imitation sentences are generated by randomly stringing together words, in the following form:

[article or pronoun] adjective1 noun1 adverb verb [article2 or pronoun2] adjective2 noun2

Here's an example:

“The common cumin childishly comfort the contrarious cat.”

Our point in this exercise is not so much to generate bad poetry and prose, as to learn about Strings, File input and output, and Java collections, in the form of ArrayList.

Step by step

You will need at least two classes – WordList and SentenceBuilder. SentenceBuilder contains your main ( ) method, and instantiates and used instances of WordList.

1. Create a class WordList. It should have a constructor that takes a filename/filepath as a String parameter.

In the WordList constructor, instantiate an ArrayList, open the filename and read the words from the specified filename/filepath into the array list. (You may want to use an object of type Scanner to do this).

Use Java Exception handling (try/catch) to handle the errors that will occur if the file you specify as an argument to the WordList constructors cannot be opened.

2. Code a method in WordList called randomWordStartingWith ( ) that takes a String parameter and returns a randomly-selected word from the ArrayList, where that word is constrained to start with the same first letter as the word passed as an argument. This will be used to make alliterative pseudo-sentences.

Your WordList class should have member variable count that the randomWordStartingWith ( ) method increments each time it searches for a word. This will be used to see how many tries it takes to find a word that matches the required first letter.

In pseudo-code, this is:

Set count = 1

Pick a random integer between 0 and the size of the ArrayList holding the words.

Select the word at the ArrayList location given by the random integer.

While ( first letter of random word does not match first letter of word passed as arg)

   Increment count

   Pick a random integer between 0 and the size of the ArrayList holding the words.

   Select the word at the ArrayList location given by the random integer.

return the randomly-selected word (which will match the required letter).

3. Provide a getter and a setter for count.

4. In your main ( ) method in SentenceBuilder, instantiate a separate WordList object for the contents of:

verb.txt

adv.txt

adj.txt

noun.txt

5. In main ( ) design your program to construct random pseudo-sentences as follows:

[article or pronoun] adjective1 noun1 adverb verb [article2 or pronoun2] adjective2 noun2

You supply a handful of articles (“The” and “A” and “An”), as well as a few pronouns such as “That”, “Your”, “My” and so on. These are just to make the pseudo-sentences seem a bit more natural. Select them randomly as needed.

Adjective1 comes from the WordList object you instantiated that holds the contents of the adj.txt file. So does Adjective2. Choose the other required parts of speech using the randomWordStartingWith ( word ) method of the appropriate WordList.

This will ensure that the sentences are alliterative, meaning that they all start with the same letter, except for the pronouns and articles you throw in.

6. Have code in your main to construct a moderate (say 100 or so) pseudo-sentences and print or otherwise display them so you can select a handful of the “best” (e.g. most novel, weirdest, or “almost-makes-sense” ones).

7. For each sentence you generate, print out the count of the number of attempts the WordList had to make to get a first-letter match. Note the pattern you see in the counts.

For this example pseudo-sentence:

“The common cumin childishly comfort the contrarious cat.”

When I ran this one, the total count for the search for all the required parts of speech starting with “c” was about 50. Your results will vary widely, of course.

Note: If the initial word starts with X or Z (I forget which), your program may be unable to find any matching alliterative words. Code a maximum number of attempts to avoid having your code loop forever.

Have Fun. I am looking forward to some interesting pseudo-sentences on this one.

noun.txt

adj.txt

adv.txt

verb.txt

Explanation / Answer

--------------------------------------------------------------------------------------------------------------------------------
import java.io.IOException;
import java.util.Random;

public class SentenceBuilder {

   private WordList advList, adjList, nounList, verbList, articleList, pronounList;
   private Random random = new Random();
  
   public SentenceBuilder() throws IOException {
      
       /*
       * TODO : Configure the base path accordingly
       * Or remove it if all the files are in the same directory
       *
       * */
       String basePath = "/home/zubair/Desktop/grammar/";

      
       /*
       * Reading adverb, adjectives, nouns, verbs
       * from text files
       */

      /* step-5*/
       advList = new WordList(basePath + "adv.txt");
       adjList = new WordList(basePath + "adj.txt");
       nounList = new WordList(basePath + "noun.txt");
       verbList = new WordList(basePath + "verb.txt");
      
       articleList = new WordList();
       pronounList = new WordList();
      
       /*
       * Articles hard-coded
       * */
       articleList.addWord("A");
       articleList.addWord("An");
       articleList.addWord("The");
      
       /*
       * Pronoun words harcoded
       */
       pronounList.addWord("I");
       pronounList.addWord("Me");
       pronounList.addWord("My");
       pronounList.addWord("We");      
       pronounList.addWord("Us");
       pronounList.addWord("He");
       pronounList.addWord("She");
       pronounList.addWord("Her");
       pronounList.addWord("You");
       pronounList.addWord("Him");
       pronounList.addWord("They");
       pronounList.addWord("Them");
       pronounList.addWord("That");
       pronounList.addWord("This");
       pronounList.addWord("Those");
       pronounList.addWord("These");
   }
  
  
   public String buildSentences(int numOfSent) {
       StringBuffer buffer = new StringBuffer();
      
       for (int i=0; i<numOfSent; i++) {
          
           String articleOrPronounOne = getArticleOrPronoun();
           String articleOrPronounTwo = getArticleOrPronoun();
          
           String adjOne = adjList.getRandomWord();
           String nounOne = nounList.getRandomWordStartingWith(adjOne);
           String advOne = advList.getRandomWordStartingWith(adjOne);
           String verbOne = verbList.getRandomWordStartingWith(adjOne);
           String adjTwo = adjList.getRandomWordStartingWith(adjOne);
           String nounTwo = nounList.getRandomWordStartingWith(adjOne);  
           String sentence = articleOrPronounOne + adjOne + " " + nounOne + " " + advOne + " " + verbOne + " " + articleOrPronounTwo + adjTwo + " " + nounTwo;
           buffer.append(sentence + System.lineSeparator());
        }
      
       System.out.println(buffer.toString());
      
       return buffer.toString();
   }
  
   /**
   * Decides whether to use article or pronoun or none
   * @return
   */
   private String getArticleOrPronoun() {
       int choice = random.nextInt(3);
       String articleOrPronoun = "";
       switch (choice) {
           case 0 :
               break;
           case 1 :
               articleOrPronoun = articleList.getRandomWord() + " ";
               break;
           case 2 :
               articleOrPronoun = pronounList.getRandomWord() + " ";
               break;
       }
      
       return articleOrPronoun;
   }
  
   public static void main(String args[]) throws IOException {

       SentenceBuilder sentenceBuilder = new SentenceBuilder();
       sentenceBuilder.buildSentences(100); /* step-6*/
   }
  
}

-------------------------------------------------------------------------------------------------------------------------

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/* step-1*/
public class WordList {
  
   protected static final int MAX_ATTEMPTS = 1000;
   private List<String> wordList;
   private Random random;
   private int count;
   /* step-1*/
   public WordList() {
       random = new Random(System.currentTimeMillis());
       wordList = new ArrayList<String>();
   }

   /* step-1*/
   public WordList(String filePath) throws IOException {
       random = new Random(System.currentTimeMillis());
       wordList = new ArrayList<String>();
       addWordsFromFile(filePath);
   }

   /**
   * Add a word to the existing list of words
   *
   * @param word
   */
   public void addWord(String word) {
       if (!wordList.contains(word)) {
           wordList.add(word);
       }
   }

   /* step-2*/
   /**
   * Get a random word from the word-pool, starting with the
   * same letter as in given word
   *
   * @return
   */
   public String getRandomWordStartingWith(String word) {
       count = 1;
       int index = random.nextInt(numOfWords());
      
       while (wordList.get(index).toLowerCase().charAt(0) != word.toLowerCase().charAt(0)
               && count < MAX_ATTEMPTS) {
           index = random.nextInt(numOfWords());
           count++;
       }
      
       if (count >= MAX_ATTEMPTS) {
           return null;
       }
       return wordList.get(index);
   }
  
   /**
   * Get a random word from the word-pool
   *
   * @return
   */
   public String getRandomWord() {
       int index = random.nextInt(numOfWords());
       return wordList.get(index);
   }
  
   /**
   * Returns the number of words in the pool
   * @return
   */
   public int numOfWords() {
       return wordList.size();
   }

  

   /* step-3*/
   public void setCount(int count) {
       this.count = count;
   }
   /* step-3*/
   public int getCount() {
       return this.count;
   }
  

   /* step-1*/
   /**
   * Reads the list of words from a given file
   * - [Full file path must be given as input]
   * - [One word per line, in the file]
   *
   * @param filePath
   * @throws IOException
   */
   public void addWordsFromFile(String filePath) throws IOException {

       BufferedReader bufferedInput = new BufferedReader(new FileReader(filePath));
       /*
       * read each line from file and add it to the List.
       */

       String inputLine;
       while ((inputLine = bufferedInput.readLine()) != null) {
           if (!inputLine.isEmpty()) {
               wordList.add(inputLine.trim());
           }
       }
       bufferedInput.close();
   }

}

--------------------------------------------------------------------------------------------------------------------------

Output

The outright Oman oratorically outglare A optic occurrences
An introducible inhospitality indomitably incurvates isonomic inaugural
Us supportless susceptibilities solitarily sibilated They simulant Sidonie
An overstrung orchises occasionally overgrown I outcast overacting
Eurocommunism escadrille endemic elegise We ectodermic exospores
unsatisfactory utilitarian unjustifiably undercutting unsolvable umber
My cagier communions competently chivying An comfiest chine
An peak posses painstakingly plain pythogenic postulator
He insolvent inventory invisibly inlace An inoffensive interludes
An alphameric anaesthesiology afar assort alt allegorizers
A away additive advisably antagonizes Him African abandons
A trafficless trawler ticklishly transferring The taut torsks
A uredinial ungulate unmixedly undersells This untempered undersleeve
A decani darn densely deems defrayable deals
That nutrient Nadine nautically narcotizes no-nonsense neurosis
benedictional boyar bimanually bevels A buckskin balustrade
They repugnant retort resoundingly recompense roasted rest-home
placeless Pinkster provisorily pilots The pentameter pellicle
ruthenious rotundas retrospectively regulate roiling rhomb
An stylographic spurges substantively schedule A sublunate stylishness
An undiscerning unfolder unsuspiciously upbuilt He united uprise
These unset underlip unisexually unsaddles We Ugric Uralic
A sable sermon stichometrically seal Saracen Sheraton
The phonic presto pectinately pulp They prolix Pizarro
metaleptical mung marvelously mercurializes He meandrous metallographers
unsaturated underhandedness upspringing understates A unblunted unction
The inflectional identity improbably imbue infernal isogeotherms
A presentative paddles pleasingly proselytised An previsional pumas
nebule nucleus nowhence nagged A nautical nosing
They epicanthic economy effectively eking extempore episode
The reproved redissolution ratably rippled They rusty reactants
An basipetal boxwoods breast-deep bootlegged The blond backside
The Aaronic areaway acceptedly assuage An abreast abampere
Me daedal document dispensatorily defoliated Them dormie deontology
They tarnished Tammanyites tardily trottings You Teucrian tatou
An eruptional edible enduringly embrittled They exanthematic eagle-hawk
The furthest fichus frequently frank Him frisky francium
notifiable negativist not nuts noctilucent Nernst
These malleable motmot mellifluously mason We microseismical matchstick
An remindful recapture roaringly reciprocates She retiring reigns
The discussible diamondback dexterously dislimns Them detonating Dyaks
A ablated Appaloosas answerably alerts We alimentative apostil
My plenipotentiary plectrons privatively perspired predicable practitioners
preludious procuratory prevalently phosphoresces A perversive penultimates
disenfranchised defecations dreamily desalts A directional debauchedness
A Memnonian mohair mathematically mint These multicultural mustaches
An Helladic hyalinizations hostilely halloing harmless histologists
The insubordinate itemization irrespectively inchoate A interior intelligencers
We airborne athetosis acrogenously achieving The asthmatic alkyne
That coalitional cupidity cravenly cumulating A collected clericalist
Aquarius acquirements acrimoniously accrete adolescent ardor
An prefab perverter participially personating palaestral pendulum
A nailless Natasha nobbily necessitated Us nummary Newman
bromic Boyd bareknuckle bay biosynthetic balloons
That self-dependent shiatsu slap strangulate I sporocystic Schwenkfelder
disingenuous dramatizations door-to-door disjoin dilatable dolomite
unwooed undergrad unthinkingly unroof An unblamable underdog
She prehistorical parazoan ploddingly pleads A phonier prunt
She fingerless forty-niner foreknowingly fugles fitting fritters
Them workable world-beaters worse whapping Him wintry way
A grouchier gat guessingly grease A gliddery gnu
A played paravanes prematurely preoccupy I protractible potentate
The biracial blighty brotherly bemire Him bronchial Belloc
progenitorial platelayers perplexedly prosing The pleochroic primely
A resistant resinoid retractively redecorate He Russ rosters
softened saiga swaggeringly spin-offs That soled sonorant
Them fixable forklifts fruitlessly frivol These fly forbiddings
Them uliginous upshot unboundedly unlearn unbacked uvulas
eggshell extinguishant ethnically extolled Her endogamic earlap
A demandable disbeliefs dazedly dilated An diamantine debasedness
Moresco mundungus macroscopically microwaves These marred mashie
Him rasping Rockford ruggedly ride He racial reposals
You poriferous portables proximo paroled Those plastered professorships
A consonantal contestants chimerically counterlight cedarn chronicity
This unmoral uproariousness unprofessionally uncapped unshifting understanding
The sunproof streetlights squintingly suntans stepwise skilly
They conjugative Clemenceau capitularly coop The consenting culpability
Her miniature Methuselah memorably mess A medical midge
A unmovable underminers uncritically upbuilding You unatoned unsolidity
statutable samaras snugly shaken supernaturalistic stalkers
The fearless fast foamily fisticuff Those flooded finner
A quintuple quaestors quibblingly quadruplicates These quartziferous quitch
tannic terrane temporisingly tallage A tonnish Trimurti
An correspondent Carlsbad compunctiously compromised Those calyciform California
mitral mystery moderately mate A merriest metropolis
A disrespectful doodads deliriously dingo denominationalism druggist
A high-grade humidifiers hopefully hand-offs hysterical huckle
Those livery lipoid loosest lases A luculent lability
She epicentral erasions experimentally empurples embryologic extemporisation
You lofty langlauf lengthily lulls Them legal Lippi
inferential Iain insolvably idealizing involuntary impressionists
The done disaccord disruptively decolourize A dull debug
These awaited assassinations antiseptically abates An aluminous Athena
laced loti learnedly legitimatize I left-handed labial
An epitaxial extravasations efficaciously enlighten extensible emetic
An pyromantic plugholes penetratingly presage This patentable petulancy
That untrue uppercut uncharitably unrig unfilmed unblessedness
Her dinkum doubtfulness deceivingly disbands A debentured doodahs
An orchidaceous ophicleides o'er overeyes Me Oxonian objectiveness
The flexed frowns fitfully fulminates freckliest fitch