Mad Libs: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 1,400: | Line 1,400: | ||
=={{header|Java}}== |
=={{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. |
<lang Java>import java.util.*; |
||
import java.util.HashMap; |
|||
import java.util.Scanner; |
|||
import java.util.StringTokenizer; |
|||
public class MadLibs |
public class MadLibs { |
||
{ |
|||
public static void main(String[] args){ |
|||
⚫ | |||
{ |
|||
⚫ | |||
String name, gender, noun; |
|||
StringBuffer storybuffer=new StringBuffer(); |
|||
⚫ | |||
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 |
|||
⚫ | |||
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 |
|||
⚫ | |||
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 |
|||
⚫ | |||
</pre> |
|||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |