简体   繁体   中英

array inside an array of object

i need to input values to an array inside an array of objects this is the method that will allow the user to enter the values

public static double addRecord(Employee[] employee) {
    Scanner in=new Scanner (System.in);
    for(int i=0; i<employee.length;i++) {
        employee[i]=new Employee();
        System.out.println("Enter the employee's ID and then name (ex: 1587 Ahmad Ashaikh):");
        employee[i].setID(in.nextInt());
        employee[i].setfName(in.next());
        employee[i].setlName(in.next());

        System.out.println("Enter the employee’s (1) BP (2) HA (3) TA (example: 4000 500 300): ");
        for(int j=0; j<3;j++) {
            employee[i].setSalary(in.nextInt(),j);
        }
        break;
    }
    return 0;
}

and that is the class that contains the values

public class Employee {

    private String fname;
    private String lname;
    private int ID;
    private int[] salary;
    private double netSalary;
    private char taxable;

    public Employee() {
        fname="unknown";
        lname="unknown";
        ID=0;
        salary=new int[0];
        netSalary=0;
        taxable='U';
    }

    public String getfName() {
        return fname;
    }

    public String getlName() {
        return lname;
    }

    public int getID() {
        return ID;
    }

    public int getSalary(int index) {
        return salary[index];
    }

    public double getNetSalary() {
        return netSalary;
    }

    public char getTaxable() {
        return taxable;
    }

    public void setfName(String fname) {
        this.fname=fname;
    }

    public void setlName(String lname) {
        this.lname=lname;
    }

    public void setID(int ID) {
        this.ID=ID;
    }

    public void setSalary(int salary,int index) {
        this.salary[index]=salary;
    }

    public void setNetSalary(double netSalary) {
        this.netSalary=netSalary;
    }

    public void setTaxable(char taxable) {
        this.taxable=taxable;
    }
}

i want to enter the salary values .. but it keeps showing me an error message:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at dd1318398p2.Employee.setSalary(Employee.java:55)
    at dd1318398p2.EmpRecord.addRecord(EmpRecord.java:72)
    at dd1318398p2.EmpRecord.main(EmpRecord.java:36)
Java Result: 1

sorry if my English is bad .. it's not my first language

This creates an array without elements - rather useless.

salary=new int[0];

If you don't know the correct number, use a List<Integer> otherwise (eg)

salary=new int[3];

You have kept the kept the salary array capacity as zero. The below statement is giving the issue -: salary=new int[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM