My question is... what is the int times for? i dont understand what i am supposed to do with it.

Here are the instructions about this method:

String[] generate(String symbol, int times)

In this method you should use the grammar to randomly generate the given number of occurrences of the given symbol and you should return the result as an array of Strings. For any given nonterminal symbol, each of its rules should be applied with equal probability. It should throw an IllegalArgumentException if the grammar does not contain the given nonterminal symbol or if the number of times is less than 0.

The full list of instructions are here if the instructions on this method are not clear enough:

https://docs.google.com/document/d/1zeXS5iqTpBErq0PNL1CbboZQW_5puVF68I-Ytnt_1_c/edit?authkey=CIWChNMI&hl=en#

Additionally, here is my code without the int times...

public String generate(String symbol){
		if(symbol == null || symbol.isEmpty())
			throw new IllegalArgumentException();
		if(!grammarContains(symbol))
			return symbol + " ";		//Ends the recursive calls if the symbol is a terminal string.
		String generated = "";			//Starts the string used to store the strings of all the recursive calls.
		String[] temp = myMap.get(symbol);		//Grabs the string array of the key being used at the moment.
		for(String value: temp[RANDOM.nextInt(temp.length)].trim().split("[ \t]+"))
				generated += generate(value);		//Recursive call till the last value is a terminal string.
		return generated;
	}
martnstepp commented: Posted homework solutions inappropriately +0

Would the int times means the length of the string you are randomizing?

You are being asked to generate an array of strings. The input variable times tells you how many strings to generate using the grammar. Assuming the generate method you wrote correctly generates a single string using the grammar, then keep that method as a helper, and implement the method asked for in the assignment by creating your array of strings based on times, and then in a loop, call your helper method the correct number of times to fill the array.

I hate when I misread something... I didnt even realize the method was a String array..... How do I change the return type to array. Does my array make sense like that? Thanks very much

Here is what I did:

public String[] generate(String symbol, int times){
		if(symbol == null || symbol.isEmpty())
			throw new IllegalArgumentException();
		if(!grammarContains(symbol))
			return symbol + " ";		//Ends the recursive calls if the symbol is a terminal string.
		String generated = "";			//Starts the string used to store the strings of all the recursive calls.
		String[] temp = myMap.get(symbol);		//Grabs the string array of the key being used at the moment.
	
			for(String value: temp[RANDOM.nextInt(temp.length)].trim().split("[ \t]+"))
				generated += generate(value, times);		//Recursive call till the last value is a terminal string.
			return generated;
	}

Hmm.. You are not really return an array of String but rather a long concatenated String. I thought that your temp is the real String array???

Well, my problem is.. i needed to change my method from

public String generate(String symbol){

to

public String[] generate(String symbol, int times){

When making the change from String to String[] ... i get the "Cannot convert from String to String[]" error on each of my return statements.

Please reread my previous post. I explained how you can use both methods to solve the problem. If you need clarification, please ask another question.

Member Avatar for coil

In short, you are returning 'generated', which is a String. According to your method header, you must return an array of Strings. That is why you are getting the error.

Yes coil, that's exactly right. I am confused about how I could return an array of strings. That is my question. Im getting frustrated because I was up all of last night preparing for a midterm today. I have 2 other midterms on monday, and this java assignment is already 3 days late. I have finished the rest of the program, this is just the last tiny bit and i cant seem to think straight.

How about this...
1)Create a string array size equal to the times you get from the argument (String[] answer = new String[times];
2)Iterate from 0 to times-1
3)Inside the iteration, generate the string grammar you want and assign to the answer
4)return the string array

That way, you will return an array of string which you need for this method.

We arent allowed to use iterators.. i am still working on this same program lmao.......

When I talk about iterating, it means you use a for-loop, not a real iterator. :)

i think im making this a lot harder than it is........... it's still not working entirely correctly.. here is all of my code

import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

public class GrammarSolver {
	private TreeMap<String, String[]> myMap; //Field for the tree map for storing the data.
	private static final Random RANDOM = new Random(); //Field for the random number used to find the random string.  

	//Created here instead of in the method for seeding.

	//Constructor that accepts an array list as a parameter.  Uses the beginning of each line as a key in a created map.
	//The rest of the line is split up into an array of strings and used as values in the map. Does this for all lines in 
	//the array. Also initializes the random variable. Throws an exception if the List passed is null or 0.
	public GrammarSolver(List<String> grammar) {

		if (grammar == null || grammar.isEmpty()) {
			throw new IllegalArgumentException();
		}
		myMap = new TreeMap<String, String[]>();
		for (String line : grammar) {
			String[] twoPart = line.split("::="); //Splits the line into two parts, key and value.
			if (grammarContains(twoPart[0]))
				throw new IllegalArgumentException(); //Checks to see if a key is already in the map.
			String[] secondPart = twoPart[1].split("[|]"); //Splits the value into an array of strings.
			myMap.put(twoPart[0], secondPart); //Adds the keys and their values into the map.
		}
	}

	//Method returns whether or not the symbol is a key in the map.  Throws an error if symbol is null or 0.
	public boolean grammarContains(String symbol) {
		if (symbol == null || symbol.isEmpty())
			throw new IllegalArgumentException();
		return myMap.containsKey(symbol);
	}

	//Method that takes a string as a parameter.  If the symbol is bull or 0 and error is returned.  If the symbol is not a 
	//key in the map then the symbol is returned as is.  If the symbol is a key in the map then a string is created that is 
	//added to on the recursive calls to the method by the non-terminal symbol and new string from the map.  Returns the combined 
	//string.	
	public String[] generate(String symbol, int times) {
		String generated = generateString(symbol, times, "");
		String[] arr = generated.split(" ");
		return arr;
	}

	private String generateString(String symbol, int times, String generated) {
		if (symbol == null || symbol.isEmpty())
			throw new IllegalArgumentException();
		if (!grammarContains(symbol))
			return symbol + " "; //Ends the recursive calls if the symbol is a terminal string.
		String[] temp = myMap.get(symbol); //Grabs the string array of the key being used at the moment.

		for (String value : temp[RANDOM.nextInt(temp.length)].trim().split("[ \t]+")) {
			if (times != 0) {
				generated += value + " ";
				return generateString(symbol, times - 1, generated); //Recursive call till the last value is a terminal string.
			} else {
				break;
			}
		}
		return generated;
	}

	//This method will return all the keys in the map.  It will return null if the map is empty.
	public Set<String> getSymbols() {
		return myMap.keySet();
	}
}
// if this part is where you are generating a string, it should be...
public String[] generate(String symbol, int times) {
  String[] arr = new String[times];  // create a string array
  for (int i=0; i<times; i++) {  // iterate from 0 to times-1
    arr[i] = generateString(symbol);  // generate each string and put in the array
  }
  return arr;
}

And in your generateString(), just generate only 1 correct string and return it...

doesnt work.. here is a copy of the main file

//
// GrammarMain contains a main program that prompts a user for the name of a
// grammar file and then gives the user the opportunity to generate random
// versions of various elements of the grammar.

import java.io.*;
import java.util.*;

public class GrammarMain {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner console = new Scanner(System.in);
        System.out.println("Welcome to the cse143 random sentence generator.");
        System.out.println();

        // open grammar file
        System.out.print("What is the name of the grammar file? ");
        String fileName = console.nextLine();
        Scanner input = new Scanner(new File(fileName));

        // read the grammar file and construct the grammar solver
        List<String> grammar = new ArrayList<String>();
        while (input.hasNextLine()) {
            String next = input.nextLine().trim();
            if (next.length() > 0)
                grammar.add(next);
        }
        GrammarSolver solver = 
            new GrammarSolver(Collections.unmodifiableList(grammar));

        showResults(console, solver);
    }

    // pre : console open for console reading, solver initialized
    // post: allows the user to repeatedly pick a grammar element to generate
    public static void showResults(Scanner console, GrammarSolver solver) {
        for(;;) {
            System.out.println();
            System.out.println("Available symbols to generate are:");
            System.out.println(solver.getSymbols());
            System.out.print("What do you want generated (return to quit)? ");
            String target = console.nextLine();
            if (target.length() == 0)
                break;
            if (!solver.grammarContains(target))
                System.out.println("Illegal symbol");
            else {
                System.out.print("How many do you want me to generate? ");
                if (!console.hasNextInt())
                    System.out.println("that's not an integer");
                else {
                    int number = console.nextInt();
                    if (number < 0)
                        System.out.println("no negatives allowed");
                    else {
                        String[] answers = solver.generate(target, number);
                        for (int i = 0; i < number; i++)
                            System.out.println(answers[i]);
                    }
                }
                console.nextLine();  // to position to next line
            }
        }
    }
}

Please provide an example of the grammar in your myMap variable (or at least the input grammar file).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.