Reputation: 5
import java.util.Scanner; import java.io.*;
public class Kazarian_MadLibs {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
File file = new File("Mad Libs 1.txt");
Scanner inputFile = new Scanner(file);
System.out.println("Please provide a word for each of the following: ");
PrintWriter answers = new PrintWriter("answers.txt");
inputFile.nextLine();
for (int i = 0; i < 18; i++)
{
System.out.println(inputFile.nextLine());
keyboard.next();
answers.println(keyboard.nextLine());
answers.close();
}
after the for loop has finished executing all 18 lines, it doesn't write any of my answers to the "answers.txt" file. What am I doing wrong here? Thanks
Upvotes: 0
Views: 76
Reputation: 159844
Move the close
statement out of the for
loop so that you're not closing the PrintWriter
in each iteration. Also you're reading from the Scanner
instance twice per iteration - just read the value once and write to file
for (int i = 0; i < 18; i++) {
System.out.println(inputFile.nextLine());
String answer = keyboard.nextLine(); // Assign variable here
answers.println(answer);
}
answers.close();
Upvotes: 3
Reputation: 3994
Move the answers.close();
outside the loop.It should work fine then.
Upvotes: 0
Reputation: 5913
Afer the first run through the loop you are closing the writer. Move the answers.close();
after the loop the close the writer after the loop has finished.
Upvotes: 0