In Java You will need at least two classes – WordList and SentenceBuilder. Sente
ID: 3806465 • Letter: I
Question
In Java
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 (breathe, respire, respire, choke, hyperventilate, hyperventilate, aspirate, burp, force out, hiccup, sigh, exhale, hold)
adv.txt (emergent, dissilient, parturient, dying, moribund, last, abridged, cut, half-length, potted, unabridged)
adj.txt (able, unable, abaxial, adaxial, acroscopic, basiscopic, abducent, adducent, nascent, emergent, dissilient, parturient)
noun.txt (object,whole,congener,living thing,organism, benthos,dwarf,heterotroph,parent,life,biont,cell)
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.
example pseudo-sentence:
“The common cumin childishly comfort the contrarious cat.”
The total count for the search for all the required parts of speech starting with “c” was about 50.
Explanation / Answer
// Hope the code meets your requirement as per my understanding,feel free to comment for any modifications,if you are
//using any ide,please make sure to increase the buffer size of the console,and change the file locations according to your comfort,either using scanner function or simply hard coding ..
package com;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class WordList {
private int count=1;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
ArrayList<String> wordsList = new ArrayList<String>();
public WordList() {
// TODO Auto-generated constructor stub
}
// E:/test.txt
public WordList(String FILENAME) {
// TODO Auto-generated constructor stub
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
for(String s:sCurrentLine.split(" ")){
wordsList.add(s.replace(".", ""));
// wordsList.add(s.replaceAll(".", "").replaceAll(",", "").replaceAll(""", ""));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public String randomWordStartingWith (String parameter){
ArrayList<String> tempList = new ArrayList<String>();
for(String word:wordsList)
{
if(word.startsWith(parameter))
{
tempList.add(word.replace(",", " ").replace(" ", " "));
}else{
count++;
}
}
Iterator<String> it = wordsList.iterator();
Random rand = new Random();
int tempSize=tempList.size();
int randomNumber=0;
if(tempSize>0)
randomNumber= rand.nextInt(tempList.size());
if(tempSize==0)
return null;
return tempList.get(randomNumber);
}
////testing
// public static void main(String args[])
// {
// WordList wr = new WordList("E:\test.txt");
// System.out.println(wr.randomWordStartingWith("c"));;
// }
}
//************************************************************************************
package com;
import java.util.Random;
public class SentenceBuilder {
public SentenceBuilder() {
}
public static void main(String[] args) {
//articles- a,an,The
//pronouns - That ,Your ,My
String files[] ={"E://verb.txt","E://adv.txt","E://adj.txt","E://noun.txt"};
String alphabets[] ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s",
"t","u","v","w","x","y","z"};
StringBuffer sb = new StringBuffer();
String character=null;
for(int i=0;i<100;i++)
{
Random rand = new Random();
int limit =0;
limit=rand.nextInt(15);
while(limit<5)
limit=rand.nextInt(15);
String tempArray[] =new String[limit];
for(int j=0;j<limit;j++){
WordList wr = new WordList(files[rand.nextInt(files.length)]);
String s=null;
while(s==null){
character=alphabets[rand.nextInt(alphabets.length)];
s=wr.randomWordStartingWith(character);
}
sb.append(s);
tempArray[j]="The total count for the search for all the required parts of speech starting with "+character +" is "+wr.getCount();
}
System.out.println(sb.toString());
for(String s:tempArray)
System.out.println(s);
sb=new StringBuffer();
}
}
}
//*************************************************************************************************
package com;
import java.util.Random;
import java.util.Scanner;
public class SentenceBuilder {
public SentenceBuilder() {
}
public static void main(String[] args) {
//articles- a,an,The
//pronouns - That ,Your ,My
String files[] ={"E://verb.txt","E://adv.txt","E://adj.txt","E://noun.txt"};
String alphabets[] ={"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s",
"t","u","v","w","x","y","z"};
StringBuffer sb = new StringBuffer();
String character=null;
//new Code as per your request
System.out.print("Enter the alphabet :");
Scanner sc = new Scanner(System.in);
character = sc.nextLine();
// for(int i=0;i<100;i++)
{
Random rand = new Random();
int limit =0;
limit=rand.nextInt(15);
while(limit<5)
limit=rand.nextInt(15);
String tempArray[] =new String[limit];
int totalCount=0;
for(int j=0;j<limit;j++){
WordList wr =null;
String s=null;
//there might be a chance that in your text files the alphabet you entered may not be there so am adding additional code for it also
// z is not present right now ,so you can check with it
int Check=0;
while(s==null){
//character=alphabets[rand.nextInt(alphabets.length)];
wr = new WordList(files[rand.nextInt(files.length)]);
s=wr.randomWordStartingWith(character);
Check++;
if(Check>10000)
{
System.err.println("The alphabet enter probably is not present in the text files provided "
+ "kindly re-run the program with another alphabet");
System.exit(0);
}
}
sb.append(s);
// tempArray[j]="The total count for the search for all the required parts of speech starting with "+character +" is "+wr.getCount();
totalCount=totalCount+wr.getCount();
}
System.out.println(sb.toString());
System.out.println("The total count for the search for all the required parts of speech starting with "+character +" is "+totalCount);
// for(String s:tempArray)
// System.out.println(s);
sb=new StringBuffer();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.