Reputation: 105
private static ArrayList<String[]> one = new ArrayList<String[]>();
...
...
btnAdd.setOnAction(e -> {
try{
String [] lineD = new String[6];
lineD[0] = txtID.getText();
lineD[1] = txtG.getText();
lineD[2] = txtBP.getText();
lineD[3] = txtD.getText();
lineD[4] = txtSP.getText();
lineD[5] = txtCons.getText();
one.add(lineD);//adds the array to ArrayList
int i = 0;
while(i<one.size()){
output.write((Arrays.deepToString(one.get(i))));
output.newLine();
i++;
}
txtID.clear();
txtG.clear();
txtBP.clear();
txtD.clear();
txtCons.clear();
txtSP.clear();
} catch (Exception t) {
System.out.println("An error has occured " + t.getMessage());
}
});
According to my logic the button is supposed to add the texts from the fields,throw them into an array, and put them into ArrayList of String arrays. The loop is supposed to write the element arrays to my file. Every single time the output is duplicated for the first addition and then the rest is written correctly.
Output:
[bob, sam, goerge, tom, smith, baker]
[bob, sam, goerge, tom, smith, baker]<------duplicate why?
[lahm, sandwhich, man, last, kitchen, food]
Upvotes: 0
Views: 60
Reputation: 13596
Here's basically what you're doing:
When the button is pressed, add the text to one
, and write all the elements of the ArrayList one
to the file output stream (?) output
.
Do you see the logic error?
After clicking once, one
is an ArrayList of size 1 with the following contents:
[bob, sam, goerge, tom, smith, baker]
When you click a second time, you add another element to the ArrayList:
[bob, sam, goerge, tom, smith, baker]
[lahm, sandwhich, man, last, kitchen, food]
And then you write both of these elements to the file:
while(i<one.size()) {
output.write((Arrays.deepToString(one.get(i))));
output.newLine();
i++;
}
What you want to do is only write the newest element to the file:
String[] lastElement = one.get(one.size()-1));
output.write((Arrays.deepToString(lastElement);
Upvotes: 2