在下面的FileWriter中,我正在写入一个名为“employee.txt”的文件。它写到文件,但最初它只是附加到文件中,而不是每次进入一个新行。从那时起,我编辑了代码,添加了"\n“,使其向下行。我的问题是,尽管从我的代码中添加或删除了"\n“,但它似乎只接受用户输入的最后一个输入。就像。如果用户希望输入2名员工,则只输入最后一个员工名。见下面的代码:
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();
}更新到打印到屏幕,以便在写入文件之前测试输出:
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;
}
}发布于 2019-04-15 02:44:17
您可以在 for循环之后创建文件编写器。并且:您只需将换行符和最后一个y对象写入文件作者!
因此:在循环之前创建文件编写器,然后在循环体中将每个employee对象写入同一个文件编写器实例!
额外提示:使用意味着什么的名称(y不,它只会混淆读者),并遵循Java命名约定。
最后:你应该研究一下“范围”这个词是什么意思。建议:不要在全球范围内声明变量,尽量在最小的有意义的范围内声明它们!
https://stackoverflow.com/questions/55681952
复制相似问题