AJ26
AJ26

Reputation: 501

FileWriter not writing all string entered at user input

In my below FileWriter below, I am writing to a file called "employee.txt." It writes to the file but originally it was only appending to the file vs going into a new line each time. I since then edited the code by adding "\n" to make it go down by a line. My issue is that despite adding or removing the "\n" from my code, it seems to only take the last input a user entered. For eg. if a user wants to enter 2 employees, it only enters the last employee name. See code below:

 static int addEmployee() throws IOException{
    int x;
    String y = null;
    Scanner emp_input = new Scanner(System.in);
    System.out.println("Enter how many employees you want to add to file:\n ");
    x = emp_input.nextInt();

    for (int i=0; i<x;i++) {
    System.out.println("Add an employee name: ");
    y= emp_input.next();
    }

    try {
    FileWriter fileWriter = new FileWriter("employee.txt", true);
    fileWriter.write("\n");
    fileWriter.write(y);
    fileWriter.close();


    } catch (IOException e) {

        e.printStackTrace();
    }

Updated to printing out to screen to test output before writing to file:

    static int addEmployee() throws IOException{
        int x;
        String y = null;
        Scanner emp_input = new Scanner(System.in);
        System.out.println("Enter how many employees you want to add to file:\n ");
        x = emp_input.nextInt();


        for (int i=0; i<x;i++) {
          System.out.println("Add an employee name: ");
          y= emp_input.next();
        }

        System.out.println(y);



        return 0;

    }
}

Upvotes: 1

Views: 225

Answers (1)

GhostCat
GhostCat

Reputation: 140573

You create that file writer after the for loop. And: you are only writing that newline and that last y object to the file writer!

So: create the file writer brfore the loop, and then write each employee object to the same file writer instance during the loop body!

Bonus hint: use names that mean something (y does not, it only confuses your readers) and follow Java naming conventions.

Finally: you should research what the term "scope" means. Suggestion: don't declare your variables globally, try to declare them in the smallest meaningful scope!

Upvotes: 2

Related Questions