开发者

I'm getting an error in my Java code but I can't see whats wrong with it. Help?

开发者 https://www.devze.com 2022-12-24 07:52 出处:网络
The error i\'m getting is in the fillPayroll() method in the while loop where it says payroll.add(employee).The error says I can\'t invoke add() on an array type Person but the Employee class inherits

The error i'm getting is in the fillPayroll() method in the while loop where it says 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. 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[ne开发者_JAVA技巧wPayroll.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. You'll be much happier.

Arrays cannot be resized once created. All the boilerplate for managing that is done by 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>();

Lists have an add() method. 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.


Since payroll is an array it would need to be

payroll[index].add(employee);


If Class B extends A:

A a=new B();

but not:

B b=new A();

0

精彩评论

暂无评论...
验证码 换一张
取 消