Write a Java program that prompts the user for input for a Mad Lib game from a t
ID: 3839410 • Letter: W
Question
Write a Java program that prompts the user for input for a Mad Lib game from a text file.
The first line of the input file will indicate the number of times the program will prompt the user for input (n). The next "n" lines contain a description of what kind of word to prompt the user (noun, adjective, etc.). Then for the rest of the file, the story will be generated by the Mad Lib contained.
The program should:
- read the file and determine how many times to prompt the user for input (based on the first line of the text file)
- prompt the user for a word using the file description
- write the user's answer to a separate text file
- and write the results of the Mad Lib to the console using the story from the input file and the user's answers from the separate text file
-----
Sample text files:
MadLibs1.txt
-------
MadLibs2.txt
Explanation / Answer
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class HelloWorld {
public static void main(String []args){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter input file name: ");
String filename = br.readLine();
BufferedReader br1 = new BufferedReader(new FileReader(filename));
FileWriter fw = new FileWriter("user_inputs.txt");
BufferedWriter bw = new BufferedWriter(fw);
String n_str = br1.readLine(), line, user_input;
int n = Integer.parseInt(n_str);
for(int i=0;i<n;i++) {
line = br1.readLine();
System.out.print(line + " ");
bw.write(br.readLine()+" ");
}
bw.close();
fw.close();
br1.readLine();
BufferedReader br2 = new BufferedReader(new FileReader("user_inputs.txt"));
for(int i=0;i<n;i++) {
System.out.print(br1.readLine());
System.out.print(br2.readLine());
}
System.out.print(br1.readLine());
System.out.print(" ");
br2.close();
br1.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Sample output:
Enter input file name: MadLibs2.txt
Noun: Galaxy
Emotion: Happiness
Girl's name: G1
Name of bad guy: B1
Letter: X
Letter: Y
Number: 1
Noun (plural): friends
Occupation: warrior
Boy's name: B2
Verb: find
Noun: N
Same boy's name: B2
Noun: N2
In the film Galaxy Wars: A New Happiness, Princess G1 sends out a call for help right before she gets captured by B1. The call reached XY-1 through a teenager named Luke and two friends. Luke finds out that he is a/an warrior and joins up with B2. Together they find the princess. At the end of the film, Luke destroys the death N while B2 covers his N2.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.