我是JAVA的新手,我为这个问题苦苦挣扎,这对我来说是非常不清楚的。我礼貌地询问是否有人可以与我讨论或教我如何回答它?谢谢。
问题:
Company类包含一组雇员,其构造函数接收4个相同长度的数组。第一个数组是String数组,是员工的名字;第二个数组是一个String数组,它是各自的地址;第三个数组是一个int数组,分别是员工编号;第四个数组是一个双数组,分别是各自的工资。
我知道如何使用公共构造函数,但我不确定公司类的构造函数。
你的帮助对我很有价值。提前谢谢。
答案 0 :(得分:2)
感觉就像一个非常简单的类结构。
public class Company {
Employee[] employees;
public Company (String[] names, String[] addresses, int[] ids, double[] salaries) {
employees = new Employee[names.length];
for (int i = 0; i < employee.length; i++) {
employees[i] = new Employee (names[i], addresses[i], ids[i], salaries[i]);
}
}
static class Employee {
String name;
String address;
int id;
double salary;
Employee (String name, String address, int id, double salary) {
this.name = name;
this.address = address;
this.id = id;
this.salary = salary;
}
}
}
如果这是学校作业并且您正在使用stackoverflow作弊,请删除问题。
答案 1 :(得分:1)
public Company(String[] names, String[] addresses, int[] employeeNumbers, double[] salaries) {
}
更好的设计是
public Company(Employee[] employees) {
}
并拥有员工类
public class Employee {
private String name;
private String address;
private int employeeNumber;
private double salary; // you may not want to use this in production
public Employee(String name, String address, int employeeNumber, double salary) {
}
// constructors, getters and setters, etc
}
根据@Kayaman评论,您似乎已经拥有了一个员工类,但出于某种原因,您不希望使用第一个构造函数来获取一组员工而不是4个数组。您希望使用带有4个数组参数的第一个构造函数,并从参数构造数组对象。这实际上是错误的编程。它会让你看起来很脏。
如果这是学校作业,你需要这样做,我猜教师可能只是想让你从中学到一些东西。但是这样的代码不应该写在生产中。
无论如何,这是您可能正在寻找的解决方案
public class Company {
private Employee[] employees;
public Company(String[] names, String[] addresses, int[] employeeNumbers, double[] salaries) {
employees = new Employees[names.length]; // assuming all arrays are of the same length
for (int i = 0;i < employees.length;i++) {
employees[i] = new Employee(names[i], addresses[i], employeeNumbers[i], salaries[i]);
}
}
}
答案 2 :(得分:0)
import java.util.ArrayList;
import java.util.Collections;
public Class Company
{
ArrayList<Employee> employees = new ArrayList<Employee>();
public Company(Employee[] newEmployees)
{
employees.addAll(newEmployees);
}
}
public Class Employee
{
public String Name;
public String Address;
public Int Id;
public Double Salary;
public Employee(string name, string address, int id, double salary)
{
this.Name = name;
this.Address = address;
this.Salary = salary;
this.Id = id;
}
}
创建新公司:
Employee[] e = {
new Employee("Bob", "Bobs address", 1, 50000),
new Employee("Jane", "Janes address", 3, 85000)
}
Company c = new Company(e);