构造函数java试图制作一个简单的程序

时间:2015-02-11 03:37:51

标签: java constructor

该程序假设将员工添加到阵列,然后为每个员工/经理分配一个分配。根据他们是经理/员工的分配是不同的金额,最后添加所有分配。

我正在努力弄清楚在添加所有员工之后如何计算总数。

package pay;

import java.util.*;



public class manager
 {
    static double allocation =0;
    public manager(String string, int i, String type) {
        // 
    }

    public static void main(String[] args)
    {
       // construct a Manager object
       manager boss = new manager("Carl Cracker", 80000, "QA");
      int total = 0;

       Employee[] staff = new Employee[3];

       // fill the staff array with Manager and Employee objects

     //  staff[0] = boss;
       staff[1] = new Employee("Harry Hacker", 0,"Dev");
       staff[2] = new Employee("Tommy Tester", 0,"QA");

       // print out information about all Employee objects
      int i;
    for (i=0; i<3; i++)
      {

       total += allocation;
      }
    }
 }



 class Employee
 {

public Employee(String string, int i, String string2) {
        // TODO Auto-generated constructor stub
    }
public double Employee(String n, int s, String type)
   {
    if (type.equals("Dev")) 
           allocation = 1000;
       else if (type.equals("QA")) 
           allocation = 500;
       else
           allocation = 250;
    return allocation;
   }
    private double getallocation()
    {
    return allocation;
    }

    private double allocation;
    public String getName()
    {
       return name;
    }
    private String name;

 }

 class Manager extends Employee
 {

    public Manager(String string, int i, String string2) {
        super(string, i, string2);
        // TODO Auto-generated constructor stub
    }
    /*
     n the employee's name
     s the salary

        */
    public double manager(String n, double s)
    {
    n= getName();
    double getAllocation = 0;
    s = getAllocation;
       s=s+300;
    return s;
   }
 }

1 个答案:

答案 0 :(得分:0)

如果您使用的是Java 8,则可以使用以下表达式对分配求和:

Arrays.stream(staff).mapToDouble(Employee::getAllocation).sum();

作为旁白(或有用的提示),这些类型的类结构通常使用复合设计模式。它看起来像这样:

interface Employee {
    double getAllocation();
    EmployeeType getType();
}

class IndividualContributor implements Employee {
    private Manager boss;
    public double getAllocation() {
        return getType().getAllocation();
    }
}

class Manager implements Employee {
    private final List<Employee> staff;
    public double getAllocation() {
        return getType().getAllocation() + 300;
    }
}

您的员工类型(目前为String)通常会实现为enum

enum EmployeeType {
    QA(500), 
    DEV(100),
    OTHER(250);

    private final double allocation;

    EmployeeType(double allocation) {
        this.allocation = allocation;
    }

    public double getAllocation() {
        return allocation;
    }
}