java中的类数组

时间:2014-01-16 02:06:25

标签: java

我是java的初学者。我试图创建嵌套类的数组,它将无法正常工作。特别是它不允许我在分配后初始化数组元素。

public class Salary {

class Person    {
    String name;
    double salary;
    void init (String n, double s)  {
        name = n;
        salary = s;
    }
}

public Salary (String args[])   {    //the input is coming in pairs: name, salary

    Person[] people;                 //creating the array
    people = new Person[10];         //allocating 10 elements in array
    int j = 0;

    for (int i = 0; i < args.length; i+=2)  {      
        people[j].init(args[i], Double.parseDouble(args[i+1]));     //trying to initialize, and that is where it's giving me an error
        System.out.format("%-15s %,10.2f%n",people[j].name, people[j].salary);
        j++;
    }
}

public static void main (String args[]) {
    new Salary(args);
 }
}

谢谢!

1 个答案:

答案 0 :(得分:6)

people = new Person[10];仅分配10 Person个对象的空间,但不会创建它们。

您需要创建对象的实例并将其分配给数组中的索引,例如

people[j] = new Person();

尝试查看Arrays了解详情

您还应该考虑使用对象构造函数而不是init方法

people[j] = new Person(args[i], Double.parseDouble(args[i+1]));

当然,这将要求您提供构造函数。