Need Help Getting A Context Free Grammar Generator Working

Hello,
This is my first real programming excercise in a college programming class. I am trying to make a context free grammar generator. I keep getting this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 2
at java.lang.String.substring(String.java:1500)
at Generator.FindCat(Generator.java:48)
at Generator.Generate_Sentence(Generator.java:28)
at Generator.main(Generator.java:16)
I'm not even sure what its trying to tell me. If anyone could take a few minutes to look at it and give me some help I'd appreciate it.
Thanks,
Mark
[email protected]
import java.util.Random;
public class Generator{
//Generate 10 Sentences
public static void main(String[] args) {
for (int a=0; a<10; a++){
System.out.println(Generate_Sentence("S"));
//Expand Categories
public static String Generate_Sentence(String category){
int startleft=0;
while (HasCategory(category)==0) {
startleft=LeftIndex(category);
category=FindCat(category,startleft);
return category;
// Find Complete Category and Separate
public static String FindCat(String category, int start){
String nextLetter="", cat="";
String left="", right="";
int endCat=0;
while ((!(nextLetter.equals(""))) || (!(nextLetter.equals(" ")))){
int z=start;
String orig = category.substring(z,z+1) ;
String folded = orig.toUpperCase() ;
if (orig.equals(folded))
cat=cat+orig;
z++;
nextLetter=category.substring(z,z+1);
endCat=z;
for (int r=0; r<start; r++){
left=left+category.substring(r,r+1);
for (int s=endCat; s<category.length(); s++){
right=right+category.substring(s,s+1);
String tempString = left+Select_Expansion(category)+right;
return tempString;
// Find Left Index
public static int LeftIndex(String category){
int e=-1;
boolean bol=false;
while (!bol){
e++;
String orig = category.substring(e,e+1) ;
String folded = orig.toUpperCase() ;
// If folding up had no effect original must have been uppercase:
if (orig.equals(folded))
bol=true;
return e;
// Check for Category 0=yes - 1=no -- WORKS FINE
public static int HasCategory(String Input) {
String original, folded_up ;
boolean b=false;
// Check each character:
for (int j = 0 ; j < Input.length() ; j++) {
// Extract single character and fold it to uppercase:
original = Input.substring(j,j+1) ;
folded_up = original.toUpperCase() ;
// If folding up had no effect original must have been uppercase:
if (original.equals(folded_up)){
b=true;
if (b)
return 0;
else
return 1;
// Select_Expansion(category) will randomly expand Category according
// to the following grammar.
static String[] Grammar= {
"S -> NAME VP",
"VP -> V NP",
"NP -> ART NN",
"NN -> ADJ NN",
"NN -> N",
"ART -> a",
"V -> is",
"V -> looks like",
"V -> acts like",
"NAME -> dr aronis",
"NAME -> mr aronis",
"NAME -> john",
"ADJ -> nice",
"ADJ -> mean",
"ADJ -> smart",
"ADJ -> stupid",
"ADJ -> hip",
"ADJ -> geeky",
"ADJ -> normal",
"ADJ -> strange",
"ADJ -> great",
"ADJ -> terrible",
"N -> person",
"N -> teacher",
"N -> fool",
"N -> tool",
static Random generator = new Random();
public static String Select_Expansion(String Category) {
// Variables:
String This_Rule = "", Rule_LHS="", Rule_RHS="";
int Number_of_Expansions=0, Expansion_to_Use=0;
// Count expansions for Category:
for (int n=0 ; n<Grammar.length ; n++) {
This_Rule=Grammar[n];
Rule_LHS = This_Rule.substring(0,This_Rule.indexOf(" ->"));
if (Rule_LHS.equals(Category)) Number_of_Expansions++;
// return error if no expansions:
if (Number_of_Expansions == 0) return "error";
//Randomly select which expansion to use:
Expansion_to_Use = Math.abs(generator.nextInt() % Number_of_Expansions);
//Go through rules while counting down through expansions of Category,
// and break with selected expansion:
for (int n=0; n<Grammar.length; n++) {
This_Rule=Grammar[n];
Rule_LHS = This_Rule.substring(0,This_Rule.indexOf(" -> "));
Rule_RHS = This_Rule.substring(This_Rule.indexOf(" -> ") + 4);
if (Rule_LHS.equals(Category) && (Expansion_to_Use ==0)) break;
if (Rule_LHS.equals(Category)) Expansion_to_Use--;
return Rule_RHS;

In general terms, any of your loops over a string should contain a test to make sure you are still within the bounds of the string. I noticed that several methods have the potential to throw exceptions like the one you saw.
You will also need (want?) to deal with the case that the string is not found - getting the substring(-1, 0) will throw an exception, too.
If you are dealing with single characters of strings, you may prefer to use the charAt(pos) method rather than substring(pos, pos+1), since comparing a character is faster (and simpler, IMHO) than comparing strings of length 1.
I also noticed, in particular, in your FindCat method, the following loopwhile ((!(nextLetter.equals(""))) || (!(nextLetter.equals(" ")))){
    int z=start;
    String orig = category.substring(z,z+1) ;
    String folded = orig.toUpperCase() ;
    if (orig.equals(folded))
        cat=cat+orig;
    z++;
    nextLetter=category.substring(z,z+1);
    endCat=z;
}You may want to move the line 'int z = start;' outside the loop, otherwise you may experience infinite looping, since you are constantly incrementing then resetting the value of z.
A common implementation technique is incremental implementation. That is, to code a single method, then test to make sure that method works as expected before moving on to the next method. This reduces the code that you will have to search for any errors when they do occur, although stack traces (as you have shown) can help in determining where an error occurs.
One final comment, a matter of style... it's considered a convention in Java to name methods and variables starting with a lowercase letter... thus 'public static String findCat' rather than 'public static String FindCat', and 'numberOfExpansions' rather than 'Number_of_Expansions'... once you get used to it, you can easily differentiate between return types, method calls, method and variable declarations and other statements. Nothing forcing you though :-)
Otherwise, it looks like you have a grasp on the language, and you understand the problem... it's just a couple of standard 'tricks' that are holding you back... which come with practice.
Good luck with your exercise!
-Troy

Similar Messages

  • I need help getting my local testing server to work - PHP/MySQL

    Hello,
    I am using DW CS5 and have installed XAMPP for my Server/PHP/DB package (which is the same as my live site).
    I have gone thru every tuitorial and all information on this subject, and unfortunately I can't get the server set up correct. Other than my page not showing in a browser (or live view) when I try to view it, DW just says: "Dynamically-related files could not be resolved because the site definition is not correct for this server" when I have index.php open and try to find the files.
    One major question is I am unsure of what folder to have as the root folder of the site, which has a public_htlm directory and www directory - or do I just use the main folder they are both located in as the root folder?
    (Not to get too deep with this first question, but I also looked at the error log file in Apache c:\xampp\apache\logs\error.log and it is not finding the following:
    [Tue Oct 09 14:26:38.573504 2012] [:error] [pid 3100:tid 1488] [client ::1:56261] script 'C:/xampp/htdocs/BusinessTube/index_e5pebna8e.php' not found or unable to stat]
    I'm guessing that the file "index_e5pebna8e.php" is a cached version of the file generated by index.php - but I'm unsure why it is not being 'found'.)
    Second question is about having to set the php.ini file to listen to port 88 as this computer also has IIS installed. I have done this, and it works with a local project directly from NetBeans (which I have to use for a PHP development class). How will this change my DW site definitions? I'm assuming that anywhere I would have localhost I will now need to have localhost:88 but once again I'm not sure.
    I am eager to get this site working locally so I can start using the new PHP skills I'm learning - any help will be GREATLY appreciated.
    Kirk

    You're getting mixed up over the meaning of public_html.
    Most hosting companies that offer PHP use the Apache web server, which has a single server root folder called htdocs. XAMPP also uses Apache, so c:/xampp/htdocs is the XAMPP server root, and its URL is http://localhost/.
    Although Apache has only one server root, virtual hosts make it possible to run multiple websites on the same server. Each virtual host is located in a separate folder that acts as the site root. It's common for this folder to be called public_html. What bregent was describing was the location of the site root on your remote server. The name of the site root in your local testing setup can be whatever you decide to call it.
    When learning to use PHP, most people use a subfolder of the Apache server root because it doesn't require further configuration. However, once you're working with real sites, it's normal to set up a virtual host for each one. I create all my virtual hosts in a folder called C:/vhosts. So for example, I might have one in C:/vhosts/site1. In the virtual hosts configuration file, I designate C:/vhosts/site1 as the root folder for a virtual host called site1, which can then be accessed as http://site1/.
    The only reason I might have a folder called public_html is if I designated C:/vhosts/site1/public_html as the site root.
    I hope that's clear. Once you understand the principle of virtual hosts, the concept of the site (or server) root becomes obvious, but it can be difficult to explain. I remember it took me a while before the concept sank in.

  • Need help getting my LaserJet 3390 scanner to work with my (iMac) Apple OS X version 10.9.4

    About two months ago i kept getting a message that my printer was not connected. When I got that fixed my scanner no longer worked and I haven't been able to find the settings to make it work. This is an excellent printer, in fine condition. Can someone please help?

    Hello dcguy,
    Welcome to the HP Support Forums!
    To get your issue more exposure I would suggest posting it in the commercial forums since this is a commercial product. You can do this at Commercial LaserJet Forums.
    The support page for your product may be helpful in the meantime: HP LaserJet 3390 All-in-One Printer
    I hope this helps!
    JERENDS
    I work on behalf of HP
    Please click “Accept as Solution” if you feel my post solved your issue, it will help others find the solution.
    Click the “Kudos Thumbs Up" to the left of the reply button to say “Thanks” for helping!

  • I need help getting my P965 Platinum board to work

    ok, I've tried researching it and searching the forums but I'm still having a lot of trouble and it's all a tad bit confusing. I've finally gotten all the stuff hooked up but I've run into trouble. My dvd drive and hard drive are both IDE and they aren't being recognized in BIOS, although I can select them as boot devices(the exact devices like ASUS DVD, not the generic cd-rom one). After it goes through th msi logo screen it goes to a screen with JMICRON stuff on it with the name of my hard drive in blue and my dvd drive in green, and to press any key to continue. If I try to boot from an xp cd in the dvd drive it gives me an :
    "CDBOOT : Couldn't find NTLDR
    Error loading OS"
    error.
    I think getting this error may have to do with the dvd drive and hard drive not being recognized in BIOS. Now, I read that one solution was putting the drivers on a floppy and booting from that. Of course I don't have one but I was able to scrounge one up from somewhere but with no blank floppies. I rewrote over a couple of the old one I had, one doesn't get recognized when I put it in and trying to boot from it give me an error and tells me to remove and media, the other is unformattable and the last one gives me an error that just says it cannot boot or there was a boot error. I download the driver folder and all I did was copy the inside of the floppy32 folder and paste that onto the floppy. Please help me, I'm on the end of my rope here. I've been dealing with one installation problem after another and now I feel even more broken now hat I know how p965 doesn't have native IDE support. I don't have SATA anything, but I do have a cd burner, a flash drive, an xp disc and possibly floppy stuff.
    Here are my specs:
    Asus 16x optical drive
    Seagate 250 gb hdd
    MSI P965 platinum motherboard
    2 gigs of Patriot extreme performance ddr2 800 RAM
    MSI geforce 880 gts(320 mb)
    OCZ Game X stream 600 watt psu
    Enermax CS-718 case
    E6600 processor
    I went to the g4 forums so I could bother them about it because I didn't want to bring up something that's already been answered on here, but I've gotten barely any help from them and all the issues I've read about on here don't exactly relate to my situation and are kinda confusing. Thank you for your help.

    Seems like some who have tried two devices on the JMICRON IDE port have had trouble. Try without the hard drive and see if you get that error. If that is the case I would try a PATA to SATA converter for your hard drive and connect it to one of the Intel SATA Ports.
    http://www.newegg.com/Product/Product.aspx?Item=N82E16812107112
    http://www.amazon.com/ADDONICS-IDE-SERIAL-CONVERTER-ADIDESA/dp/B000090169
    http://www.compusa.com/products/product_info.asp?product_code=339900#ts
    http://www.xpcgear.com/ide2sata.html
    http://www.ubuyitdirect.com/-p-1045.html?currency=USD
    http://www.satasite.com/sata-ide-converter.htm
    http://www.pcgears.com/default.aspx?oid=187150
     

  • I need help getting new authorization codes for digital copies

    I need help getting new authorization codes for digital copies of movies. Can someone help me out?

    There's a lot of results in Google when you search for this but unfortunately refreshing the page doesn't seem to generate a different code anymore. Mine also says already redeemed

  • TS1538 i need help because i need help getting my ipod touch to connect to windows vista and

    i need help getting my ipod touch to connect to windows because it keeps saying udb device not recognized and i tr\]ied restarting the settings!!!!!

    Have you tried here:
    iOS: Device not recognized in iTunes for Windows

  • I need help getting itunes on my new computer. old one crashed

    My old computer crashed, I downloaded iTunes on my new computer and need help getting all of my stuff on it that I had. I did 'home share' to see if that worked, and it didnt.
    Also, on my old computer, when I synced my iPad & my husbands iPod, it didnt sync any music or podcasts, no videos-and i went through each category seperately to sync it and it didnt work. So I can't sync my devices to the new iTunes bc not everything is on there that i have purchased.

    It has always been very basic to always maintain a backup copy of your comuter for just this occasion.  Use your backup copy to put everything on the new computer.
    If for some reason you have failed to maintain a backup, not good, then you can redownload some itunes purchases in some countries:
    Downloading past purchases from the App Store, iBookstore, and iTunes Store

  • TS4268 I need help getting my face time and imessage to work.

    I need help getting my face time and imessage to work. It is saying wating for activation. I just got my iphone 5 2 days ago. I have reset it from the phone and from itunes on the computer, made sure I'm attached to wifi.

    The 3 basic troubleshooting steps are these in order: 1. Restart your iphone  2.  Reset your settings/iphone  3.  Restore your iphone.  Since your iphone is only a couple of days old, you should backup your device before restoring.  If you don't have anything on your iphone that you care to lose, then simply restoring without a backup is fine.  A quick reset of pressing the sleep/wake button (top of iphone) and your home button simultaneously and holding it until the silver Apple logo appears. 

  • I need help getting my OS X Mavricks download to work and start downloading but it wont work

    i need help getting my OS X Mavricks download to work and start downloading but it wont work

    Contact http://www.apple.com/support/mac/app-store/contact/. They're responsible for getting this abysmal delivery system to work.

  • I need help getting my os x mountain lion to work for my pro tools

    I need help getting my os x mountain lion to work for my pro tools

    Since you provide no details I can do nothing but guess, so perhaps this will help:
    http://avid.force.com/pkb/articles/en_US/how_to/Upgrading-to-Mac-OS-10-8?popup=t rue&NewLang=en&DocType=1080
    http://avid.force.com/pkb/articles/en_US/compatibility/Avid-Software-and-Mac-OS- X-10-8?popup=true&NewLang=en&DocType=1083
    If you continue to have problems, you probably should contact Avid support.
    Regards.

  • I need help getting my printer to work

    I need help getting my printer to work

    http://h30434.www3.hp.com/t5/Printer-Networking-and-Wireless/Want-Good-Answers-Ask-Good-Questions/td...
    Say thanks by clicking "Kudos" "thumbs up" in the post that helped you.
    I am employed by HP

  • I need help in finding a free update for my windows 7.5 mobile

    I need help in finding a free update for my mobile 7.5 windows phone
    Message was edited by: chevycamer427

    http://www.windowsphone.com/en-us/store/app/adobe-reader/bc4f319a-9a9a-df11-a490-00237de2d b9e
    [topic moved to Windows Phone subforum]

  • Now i have tryied everything i need help getting premier pro trial real help pls!

    now i have tryied everything i need help getting premier pro trial real help pls!

    Hi,
    Are you facing issues installing Premiere pro trial?
    Please mention your operating system.
    Error(If you're getting any)
    Thank you,
    Mohd Naseem

  • My old iMac and OS 10.4 will not accept the New iTunes Version 10 application and I can't get past the screen offering to download iTunes 10.  This is wrong and I need help getting past this situation. Help!

    My old iMac and OS 10.4 will not accept the New iTunes Version 10 application and I can't get past the screen offering to download iTunes 10.  This is wrong and I need help getting past this situation. Help!

    Sure, you can get around it if you don't need the newest version of iTunes. I still use version 7.5 because the newer versions didn't strike me as offering anything I needed.
    If you do need a version 10-something then you will have to upgrade your operating system to Leopard (fi your computer will support it) at least.  If you need 10.5 for some reason then there's no getting around it, you will have to buy a new computer.

  • I need help getting the license number for Adobe Photoshop Elements. However, It doesn't recognize me as an authorized user. Can someone help?

    I need help getting the license number for Adobe Photoshop Elements. However, It doesn't recognize me as an authorized user. Can someone help?@

    I am having the same problem...did you ever fix it?

Maybe you are looking for

  • How to export a large, high-rez Keynote'08 file as a QT movie?

    I have used Keynote '08 to create a 1.6GB presentation, 1024 x 768 resolution, 940 slides of stills and animation clips, navigatable hyperlinks on every slide. It plays and navigates perfectly well in Play mode. The presentation would of course be mo

  • How do I import document from my desk top into pages on my ipad?

    How do I import document from my desk top into pages on my ipad?

  • Internal Table Comparision

    Hi, I have two internal tables both have them large no of records. For ex: it_large this table has about 150,00-200,00 records on average. It has 3 fields item_id, text and type. and it_small this tables has about 60,000-80,000 records on average. Ju

  • Slow Finder Icon Redraw Fuzzy Finder Icons

    When I open a window in the Finder (Applications for example) all the icons are displayed as generic application/folder icons and will slowly redraw with the correct app icons (Apple apps like iTunes, Safari, etc included). Also, if I click on an app

  • Is it possible to add an option to pay online OR mail in a check?

    While my form is functioning correctly, it leads people to think they can ONLY pay online- I want to make it so they can submit their information without paying online if they so choose.  Right now there is only a "proceed to checkout" paypal button,