We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hey all, need to fix this string (I think?). I'm trying to create a code that will insert random verbs, nouns, etc... wherever I choose. I've been able to load the data correctly and was able to write a code that inserts a random noun into a sentence, but now I'm stuck. After loading the verbs data, however, I've run into the issue that the code now duplicates every word of the sentence, going from something like "Bob really likes (random noun)" to "Bob Bob really really (random verb) %verb% (random noun) %noun%". Anyone got any ideas? Code is below:
String[] nouns; String[] verbs; int fileCount = 0;
String storyTemplate1 = "Bob really %verb% %noun%"; void setup() { nouns = loadStrings("Nouns.txt"); //THIS^ LOADS THE NOUNS LIST FROM THE DATA FOLDER... //MUST BE EXACT NAME OF TEXT FILE WITHIN DATA FOLDER verbs = loadStrings("Verbs.txt"); String story1 = instantiateStory(storyTemplate1); String[] output = new String[1]; output[0] = story1; saveStrings("story1.txt", output); }
String instantiateStory(String template) { String story = ""; //TO DO: Fill in nouns and Stuff //MUST USE SPLIT (SEE REFERENCE) FOR FINAL PROJECT String[] splitTemplate = split(template, " "); for (int i = 0; i < splitTemplate.length; i++) { if (splitTemplate[i].equals("%noun%")) { //Adds a random noun to story story = story + getRandomNoun() + " "; } else { story = story + splitTemplate[i] + " "; } if (splitTemplate[i].equals("%verb%")) { story = story + getRandomVerb() + " "; } else { story = story + splitTemplate[i] + " "; } } return story; }
String getRandomNoun() { int randomIndex = (int)random(0,nouns.length); return nouns[randomIndex]; }
String getRandomVerb() { int randomIndex = (int)random(0,verbs.length); return verbs[randomIndex]; }
Answers
you had it almost, except that part where the logic is flawed (computers are stupid)
see, when it's not a noun he adds the word. but then he checks if it is not a verb and if not adds the same word again. Bad. Hence the error.
see my solution in the last post: check noun, check verb and only then insert word (using a
if.... else if.... else.....
beast )EDIT: Nevermind, I got it. Thank you, Chris.
great!