A lot of posts exist on this assignment - most wanting to know how to do it. Please let me figure out the rest of this on my own - I'm just looking for one or two bits of help, not someone to do my assignment for me.
The assignment is to write a program that implements syntax rules to build random sentences.
When I implement my code, I get a stack overflow, but I modeled it after the sample code that doesn't have that error. I know it's something with my if...else
statement in sentence();
causing it.
Here is my code:
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
public class RecursiveSyntax {
private static final String[] conjunction = { "and", "or", "but", "because" };
private static final String[] properNoun = { "Fred", "Jane", "Richard Nixon", "Miss America" };
private static final String[] commonNoun = { "man", "woman", "fish", "elephant", "unicorn" };
private static final String[] determiner = { "a", "the", "every", "some" };
private static final String[] adjective = { "big", "tiny", "pretty", "bald" };
private static final String[] intransitiveVerb = { "runs", "jumps", "talks", "sleeps" };
private static final String[] transitiveVerb = { "loves", "hates", "sees", "knows", "looks for", "finds" };
public static void main(String[] args) {
List<String[]> arrayList = new ArrayList<>();
arrayList.add(conjunction);
arrayList.add(properNoun);
arrayList.add(commonNoun);
arrayList.add(determiner);
arrayList.add(adjective);
arrayList.add(intransitiveVerb);
arrayList.add(transitiveVerb);
while (true) {
sentence();
System.out.println(".\n\n");
try {
Thread.sleep(3000);
}
catch (InterruptedException e) {
}
}
}
private static void sentence() {
int c = (int)(Math.random()*conjunction.length);
double x = Math.random();
if (x < 0.2)
simpleSentence();
else
simpleSentence();
System.out.print(conjunction[c]);
sentence();
}
private static void simpleSentence() {
nounPhrase();
verbPhrase();
}
private static void nounPhrase() {
int pn = (int)(Math.random()*properNoun.length);
System.out.print(" "+ properNoun[pn] + " ");
}
private static void verbPhrase() {
int iv = (int)(Math.random()*intransitiveVerb.length);
System.out.print(" " + intransitiveVerb[iv]);
}
}
I'm just looking for two things:
- How do I fix my stack overflow error
- What am I doing wrong with my
if..else
statement?
I need it to call simpleSentence()
some of the time, and on a random weighted percent of the time call simpleSentence
, then print a random conjunction from the conjunction array, then run sentence()
again without stack overflow errors.
The BNF for this part is:
<sentence> ::= <simple_sentence> [ <conjunction> <sentence> ]
<simple_sentence> ::= <noun_phrase> <verb_phrase>
A copy of the assignment requirements can be found here (if it's needed for clarity) Par 1 Recursive Syntax: http://math.hws.edu/eck/cs225/s10/lab3/.
sentance
will call itself 80% of the time.