数组内的一个对象数组

时间:2014-07-13 14:04:15

标签: java arrays object arrayobject

我需要将值输入到对象数组中的数组,这是允许用户输入值的方法

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;
}

,这是包含值

的类
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;
    }
}

我想输入工资值..但它会一直显示错误信息:

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

对不起,如果我的英语不好......那不是我的第一语言

2 个答案:

答案 0 :(得分:2)

这会创建一个没有元素的数组 - 相当无用。

salary=new int[0];

如果您不知道正确的号码,请使用List<Integer>否则(例如)

salary=new int[3];

答案 1 :(得分:0)

您已将保留的薪水阵列容量保持为零。以下声明给出了问题 - : salary = new int [0];