'Looping a file writer

I'm building a relativley simple stock system to account for books I own in a file, however I'm having trouble iterating the inputs.

Here are my imports:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

and the globals:

private static File myFile = new File("libraryList.txt");
private static ArrayList<String> bookTitles = new ArrayList<String>();
private static Scanner inputScanner = new Scanner(System.in);

So the array "bookTitles" stores the title, author, ISBN and genre of a book - all of which have inputs that work. I can input all of the information for one book - and it'll be written successfully.

The main issue comes when attempting to write a second book in.

My "add another book" loop works, however it won't write any further than just the first book entered.

System.out.println("Would you like to add another book? Y/N");
            String addAnother = inputScanner.nextLine(); //assigns the answer for addAnother to the variable
            if (addAnother.equals("N")) {
                addNewBook = false; //if they don't want to add another, end the loop.
                WriteToFile();
            }

same goes for the file writer - it all works fine, but only for the first iteration.

public static void WriteToFile() {
    try {
        FileWriter myWriter = new FileWriter(myFile.getName(), true); //True means append to file contents, False means overwrite
        System.out.println("This is the contents of the file:");
        myWriter.write(""); //makes a space between each book
        myWriter.write(bookTitles.get(0)+(" ")); // adds the current list to the file
        myWriter.write(bookTitles.get(1)+(" "));
        myWriter.write(bookTitles.get(2)+(" "));
        myWriter.write(bookTitles.get(3)+("\n\n"));
        myWriter.close();
        System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

I'm aware that the issue stems from me only accessing units 0-3 from the array, however I can't come up with an iteration that works properly with the rest of my code - everything I've attempted thus far has just broken.

Here's the pastebin link for the full code:

https://pastebin.com/BiXBuu88



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source