Mad Libs: Difference between revisions

1,409 bytes removed ,  4 years ago
No edit summary
Line 1,400:
 
=={{header|Java}}==
I tried to fix this... but this is my first one.
This is extremely messy code. There's bound to be a more optimal way of doing this.
 
<lang Java>import java.util.Map*;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
 
public class MadLibs {
{
public static void main(String[] args){
Scanner sinput = new Scanner(System.in);
{
Scanner s=new Scanner(System.in);
String linename, gender, noun;
StringBuffer storybuffer=new StringBuffer();
System.out.printlnprint("Enter a "+name: id");
name = input.next();
//Accept lines until empty line is entered
while(!(line=s.nextLine()).isEmpty())
System.out.print("He or she: ");
storybuffer.append(" "+line);
gender = input.next();
//Remove first space
System.out.print("Enter a noun: ");
storybuffer.delete(0, 1);
noun = input.next();
String story=storybuffer.toString();
//Split
Champak System.out.println("\f" + name + " went for a walk in the park. He" found+ gender + "\nfound a hippo" + noun + ". Champak" + name + " decided to take it home. ");
StringTokenizer str=new StringTokenizer(story);
String word;
StringBuffer finalstory=new StringBuffer();
}
}
//Store added elements
Map<String,String> hash=new HashMap<String,String>();
while(str.hasMoreTokens())
{
word=str.nextToken();
if(word.contains("<"))
{
String add="";
//Element prompt could be more than one word
if(!word.contains(">"))
{
//Build multi-word prompt
String phrase="";
do{
phrase+=word+" ";
}while(!(word=str.nextToken()).contains(">"));
word=phrase+word;
}
//Account for element placeholder being immediately followed by . or , or whatever.
if(word.charAt(word.length()-1)!='>')
add=word.substring(word.lastIndexOf('>')+1);
//Store id of element in hash table
String id=word.substring(0,word.lastIndexOf('>')+1);
String value;
if(!hash.containsKey(id))
{
//New element
System.out.println("Enter a "+ id);
value=s.nextLine()+add;
hash.put(id, value);
}
//Previously entered element
else
value=hash.get(id);
word=value;
}
finalstory.append(word+" ");
}
System.out.println(finalstory.toString());
s.close();
}
}</lang>
 
{{out}}
<pre>
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
 
Enter a <name>
Champak
Enter a <he or she>
He
Enter a <noun>
hippo
 
Champak went for a walk in the park. He found a hippo. Champak decided to take it home.
 
</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
Anonymous user