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());
}
});
根据我的逻辑,按钮应该从字段中添加文本,将它们放入数组中,然后将它们放入String数组的ArrayList中。该循环应该将元素数组写入我的文件。 每次输出都会在第一次添加时重复,然后其余的都会正确写入。
输出:
[bob,sam,goerge,tom,smith,baker]
[bob,sam,goerge,tom,smith,baker]&lt; ------重复为什么?
[lahm,sandwhich,man,last,kitchen,food]
答案 0 :(得分:2)
这基本上是你正在做的事情:
按下按钮时,将文本添加到one
,并将ArrayList one
的所有元素写入文件输出流(?)output
。
你看到了逻辑错误吗?
单击一次后,one
是一个大小为1的ArrayList,其中包含以下内容:
[bob, sam, goerge, tom, smith, baker]
当您再次单击时,将另一个元素添加到ArrayList:
[bob, sam, goerge, tom, smith, baker]
[lahm, sandwhich, man, last, kitchen, food]
然后你将这两个元素都写到文件中:
while(i<one.size()) {
output.write((Arrays.deepToString(one.get(i))));
output.newLine();
i++;
}
您要做的只是将最新元素写入文件:
String[] lastElement = one.get(one.size()-1));
output.write((Arrays.deepToString(lastElement);