97.5k views
4 votes
Java help. I am doing a mad libs code for a class and I’m using file I/O to let the program read and write. The code keeps repeating after reading only one line of the text file and after prompts user to input an adj, noun, etc and then after reading the next line it does the same. Is there a way to prompt it to ask user only one time and so it can display in the console?

User Necmttn
by
7.5k points

1 Answer

3 votes

Answer:

import java.io.*;

public class MadLibs {

public static void main(String[] args) {

try {

BufferedReader reader = new BufferedReader(new FileReader("madlibs.txt"));

String line = reader.readLine();

// Prompt the user to input all the words at once

System.out.println("Enter an adjective:");

String adj = System.console().readLine();

System.out.println("Enter a noun:");

String noun = System.console().readLine();

System.out.println("Enter a verb:");

String verb = System.console().readLine();

// Loop through the lines of the text file

while (line != null) {

// Replace placeholders with user input

line = line.replaceAll("<adjective>", adj);

line = line.replaceAll("<noun>", noun);

line = line.replaceAll("<verb>", verb);

// Print the line to the console

System.out.println(line);

// Read the next line of the text file

line = reader.readLine();

}

// Close the reader

reader.close();

} catch (IOException e) {

System.out.println("An error occurred: " + e.getMessage());

}

}

}

Step-by-step explanation:

This code has been altered so that it requests the user to enter an adjective, noun, and verb before reading the text file. Subsequently, it iterates through the lines of the file, replacing the placeholders with the user input and displaying the line to the console.

User Kennytm
by
7.0k points