Java 如何确保我的方法只要求一次文件名并向其中添加对象
我的超类中有一个将数据写入文件的方法,该方法在我的子类中被重写。问题是在运行时,我三次收到创建新文件的提示。这是我的密码:Java 如何确保我的方法只要求一次文件名并向其中添加对象,java,oop,inheritance,polymorphism,filewriter,Java,Oop,Inheritance,Polymorphism,Filewriter,我的超类中有一个将数据写入文件的方法,该方法在我的子类中被重写。问题是在运行时,我三次收到创建新文件的提示。这是我的密码: public class Employee { protected String name; protected String employeeNum; protected String department; protected char type; protected BufferedWriter printer; } p
public class Employee
{
protected String name;
protected String employeeNum;
protected String department;
protected char type;
protected BufferedWriter printer;
}
public void writeData() throws IOException
{
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the name of the new file for next week");
String newFile = sc.nextLine();
printer = new BufferedWriter(new FileWriter(newFile + ".txt"));
String data= getData();
printer.write(data);
}
protected String getData()
{
return name + " " + employeeNum + " " + department + " " + type;
}
public class Commission extends Employee
{
private int weeksStart;
private double baseWeeklySalary;
private double salesWeekly;
private double totalSales;
private double commissionRate;
}
@Override
protected String getData()
{
return name + " " + employeeNum + " " + department + " " + type + " " + weeksStart + " " + baseWeeklySalary + " " + salesWeekly + " " + totalSales + " " + commissionRate;
}
假设所有相关承包商都在那里。我还有两个子类;试图实现相同writeData()方法的时薪和工资。当我遍历我的ArrayList of employees并尝试writeData()时,
当我只需要创建一个文件时,它会为每种类型的员工创建一个新文件
Public class PayRoll
{
Private ArrayList < Employee > employees;
public class PayRoll()
{
employees = new ArrayList Employee > ();
}
public void endOfDay()
{
for (int I = 0: i < employees.size (): i++)
{
employees.get(i).writeData():
}
}
}
公共类工资单
{
私人ArrayListemployees;
公共类工资单()
{
员工=新阵列列表员工>();
}
公众假期结束日()
{
对于(inti=0:I
我将此方法分为两部分。一个部分向用户请求文件名,然后打开它,等等。这个部分不需要被覆盖。唯一需要重写的部分是生成数据字符串的部分,该数据字符串可以放在自己的方法中:
public class Employee {
/* Data members, omitted for brevity's sake */
public void writeData() throws IOException {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter the name of the new file");
String newFile = sc.nextLine();
printer = new BufferedWriter(new FileWriter(newFile + ".txt"));
String data = getData();
printer.write(data);
}
protected String getData() {
return name + " " + employeeNum + " " + department + " " + type;
}
}
public class Commission extends Employee {
/* Data members, omitted for brevity's sake */
@Override
protected String getData() {
return name + " " + employeeNum + " " + department + " " + type + " " + weeksStart + " " + baseWeeklySalary + " " + salesWeekly + " " + totalSales + " " + commissionRate;
}
}
添加一个静态变量isFileCreated,在创建文件后将其设置为true,并且仅当该变量为false时才执行该块。您如何实例化您的
Employee
实例,您可以添加它吗?您的writeData()方法似乎不在类中……我已经更新了问题,以反映我试图从何处调用方法。谢谢!我想知道如何分解它,这正是我需要的我这里有个问题,如果我的ArrayList中有多个员工,如上所述,每个员工都会被调用。如何创建单个文件?@MacMcGuy在循环外部创建文件,并将其传递给构造函数中的每个Emploee
对象