将数组传递给testclass构造函数

时间:2009-09-30 12:52:32

标签: java arrays constructor

我需要传递一个未在方法中定义的1d数组。

我需要创建一个测试类,然后自己创建数组。

我只是不确定语法。

示例,这是我的公司类:

public class Company
{
String name;
String address;
Employee employeeList[] = new Employee[3];

public Company (String name, String address ,
                     Employee employeeList, String jobTitle )
{
    this.name = name;
    this.address = address;
}
public void printDetails()
    {
        for(int i = 0; i>employeeList.length;i++)
        {
            System.out.println(" The companys name is " + name);
            System.out.println(" The Companys Address is "+ address);
            System.out.println("The List of employees are " + employeeList[i].name);
            System.out.println("The Titles of These Employees are " + employeeList[i].jobTitle);
        }
    }
}

但我的测试类是问题所在。

我从哪里开始?我是否应该将arrays(employees)加入其中?

public class TestCompany
{
public static void main(String[] args)

{                                                                        employees?
Company hungryBear = new Company("hungryBear ", "Those weird apartments ",//////   );
}
}

2 个答案:

答案 0 :(得分:1)

public Company (String name, String address ,
                     Employee employeeList, String jobTitle )

应该是:

public Company (String name, String address ,
                     Employee []employeeList, String jobTitle )

现在,您没有将数组传递给您的方法,而是传递实例。您需要告诉Java您正在传递数组。

编辑了员工班的新知识......

此外,在传递数组之前,您需要在main函数中构建数组。像这样:

public static void main(String[] args){                                                                        
    Employee [] employeeList = {
        new Employee("Samuel T. Anders", "Player, Caprica Buccaneers"),
        new Employee("William Adama", "Commander, Battlestar Galactica")
    };

    Company hungryBear = new Company("hungryBear ", "Those weird apartments ", employeeList);
}

不确定这会回答你的问题,但也许这会帮助你传递一点点数组的语法。

另一种编辑,另一种初始化数组的方法:

Empolyee [] employeeList = new Employee[2];
employeeList[0] = new Employee("Samuel T. Anders", "Player, Caprica Buccaneers");
employeeList[1] = new Employee("William Adama", "Commander, Battlestar Galactica");

答案 1 :(得分:0)

Empolyee [] employeeList = new Employee[2];


for(int i=0;i<2;i++){
  Scanner input = new Scanner(System.in);

  employeeList[i] = input.next();
}