0

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

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

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

4

2 回答 2

2

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 (e.g.)

salary=new int[3];
于 2014-07-13T14:12:42.803 回答
0

您已将保留的工资数组容量保持为零。以下语句给出了问题 -: salary=new int[0];

于 2014-07-13T14:34:54.323 回答