N. Kazarian
N. Kazarian

Reputation: 5

Input not getting written to a file after a for loop

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

Answers (4)

Reimeus
Reimeus

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

Dylan Meeus
Dylan Meeus

Reputation: 5802

You close the writer answers on each iteration of the loop.

Upvotes: 3

Roney Michael
Roney Michael

Reputation: 3994

Move the answers.close(); outside the loop.It should work fine then.

Upvotes: 0

Lukas Eichler
Lukas Eichler

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

Related Questions