[英]I'm getting an error in my Java code but I can't see whats wrong with it. Help?
The error i'm getting is in the fillPayroll() method in the while loop where it says payroll.add(employee). 我得到的错误是在while循环的fillPayroll()方法中,它说的是payroll.add(employee)。 The error says I can't invoke add() on an array type Person but the Employee class inherits from Person so I thought this would be possible.
该错误表明我无法在数组类型Person上调用add(),但是Employee类继承自Person,因此我认为这是可能的。 Can anyone clarify this for me?
谁能为我澄清一下?
import java.io.*;
import java.util.*;
public class Payroll
{
private int monthlyPay, tax;
private Person [] payroll = new Person [1];
//Method adds person to payroll array
public void add(Person person)
{
if(payroll[0] == null) //If array is empty, fill first element with person
{
payroll[payroll.length-1] = person;
}
else //Creates copy of payroll with new person added
{
Person [] newPayroll = new Person [payroll.length+1];
for(int i = 0;i<payroll.length;i++)
{
newPayroll[i] = payroll[i];
}
newPayroll[newPayroll.length] = person;
payroll = newPayroll;
}
}
public void fillPayroll()
{
try
{
FileReader fromEmployee = new FileReader ("EmployeeData.txt");
Scanner data = new Scanner(fromEmployee);
Employee employee = new Employee();
while (data.hasNextLine())
{
employee.readData(data.nextLine());
payroll.add(employee);
}
}
catch (FileNotFoundException e)
{
System.out.println("Error: File Not Found");
}
}
}
Instead of using an array use an ArrayList
. 代替使用数组,而使用
ArrayList
。 You'll be much happier. 您会更加快乐。
Arrays cannot be resized once created. 数组一旦创建便无法调整大小。 All the boilerplate for managing that is done by
ArrayList
. 用于管理的所有样板文件均由
ArrayList
完成。 Using arrays with subclasses in elements has other issues too (around covariance). 在元素中使用带有子类的数组也存在其他问题(围绕协方差)。 Probably the only line you need to change is:
您可能需要更改的唯一一行是:
private final List<Person> payroll = new ArrayList<Person>();
List
s have an add()
method. List
具有add()
方法。 Arrays don't. 数组没有。
If for whatever reason you can't use collections. 如果出于某种原因您不能使用集合。 you want to turn:
你想转:
payroll.add(employee);
in to: 进入:
this.add(employee);
payroll is an array. 工资单是一个数组。 You are invoking method on an array.
您正在调用数组上的方法。 This is not possible.
这是不可能的。
由于工资单是一个数组,因此需要
payroll[index].add(employee);
If Class B extends A: 如果B类扩展了A:
A a=new B();
A a = new B();
but not: 但不是:
B b=new A();
B b = new A();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.