简体   繁体   English

构造函数不创建对象-Java

[英]Constructors not Creating Object — Java

I've been wrestling with this problem in one of my programs for about a week now, and I have no idea what I am doing wrong. 大约一个星期以来,我一直在自己的一个程序中解决此问题,但我不知道自己在做什么错。 For this assignment I'm basically making an array of Employee objects with 3 different types of employees (commission, salary, hourly). 对于此分配,我基本上是用3种不同类型的雇员(佣金,薪水,小时数)组成一个Employee对象数组。 All three of the sub-classes extend the Employee class, which is abstract. 这三个子类都扩展了Employee类,它是抽象的。

Here is my code that calls the constructors for each class type: 这是我的代码,它为每种类类型调用构造函数:

    public boolean addEmployee(int empType, String first, String last, char mi, char gen, int empNum, boolean full, double amount)
    {
    employeeCount += 1;

    if (employeeCount > EMPLOYEES_MAX) {
        System.out.println("ERROR: ARRAY FULL. UNABLE TO ADD NEW EMPLOYEE");
        return false;
    }

    else {
        switch (empType) {
            case 1:
            employees[employeeCount] = new HourlyEmployee(first, last, mi, gen, empNum, full, amount);
            break;

            case 2:
            employees[employeeCount] = new SalaryEmployee(first, last, mi, gen, empNum, full, amount);
            break;

            case 3:
            employees[employeeCount] = new CommissionEmployee(first, last, mi, gen, empNum, full, amount);
            break;
        }
        return true;
    }
}

And here is the constructor for the salary employee, the other 2 are pretty much teh same as this. 这是薪水员工的构造函数,其他两个与此基本相同。

public class SalaryEmployee extends Employee
{
private double salary;

public SalaryEmployee(String first, String last, char midInit, char gen, int empNum, boolean full, double sal)
{
    super(first, last, midInit, gen, empNum, full);
    salary = sal;
}

The super constructor I have written which is called by this constructor follows: 我编写的由该构造函数调用的超级构造函数如下:

abstract class Employee
{
protected String firstName;
protected String lastName;
protected char middleInitial;
protected boolean fullTime;
protected char gender;
protected int employeeNum;

public Employee(String first, String last, char midInit, char gen, int empNum, boolean full)
{
    firstName = first;
    lastName = last;
    middleInitial = midInit;
    employeeNum = empNum;
    fullTime = full;

    switch (gen) {
        case 'M': case 'F': 
        case 'm': case 'f':
        gender = gen;
        break;

        default:
        gender = 'F';
    }
}

As I've said before, I have no idea why its not creating the objects like it should. 就像我之前说过的,我不知道为什么它不创建应有的对象。 Whenever I go to print out the array or sort it or anything I always get either null or a null pointer exception. 每当我打印输出数组或对其进行排序时,总是得到null或null指针异常。

Any help would be greatly appreciated, thank you all so much! 任何帮助将不胜感激,非常感谢大家!

EDIT: 编辑:

Ok, heres where my Employee array is initialized. 好的,这里是我的Employee数组初始化的地方。

public class EmployeeList
{
private final int EMPLOYEES_MAX = 50;
private Employee employees[];
private int employeeCount;

public EmployeeList()
{
    employees = new Employee[EMPLOYEES_MAX];
    employeeCount = 0;
}

When I run it its like its still going through the constructors because the default method is not run, I just get null for some odd reason. 当我运行它时,由于未运行默认方法,就像仍在构造函数中运行一样,由于某种奇怪的原因,我只会得到null。 Heres the output: 继承人的输出:

Choose from the following options: 1 Add Employee 2 Process Employees by Type Submenu 3 Remove Employee 4 Sort Employees 5 Calculate Weekly Payout 6 Calculate Bonus 7 Annual Raises 8 Reset Week 0 Quit Option: 1 从以下选项中选择:1添加员工2按类型处理员工子菜单3删除员工4排序员工5计算每周支付6计算奖金7年度薪水8重设周0退出选项:1

  1. Hourly 每小时
  2. Salary 薪水
  3. Commission Enter Choice: 1 佣金输入选项:1

Enter Last Name: Doe 输入姓氏:Doe

Enter First Name: Jane 输入名字:Jane

Enter Middle Initial: M 输入中间名首字母:M

Enter Gender: F 输入性别:F

Enter Employee Number: 1 输入员工编号:1

Full Time? 全职? (y/n): y (y / n):y

Enter wage: 14 输入工资:14

Employee Added to List 员工已添加到列表

null 空值

Main Menu 主菜单

The null comes from my main class that calls a listAll() method, its supposed to list everything in the array. null来自我的主类,该主类调用listAll()方法,该方法应列出数组中的所有内容。 but instead just returns null. 但只会返回null。

EDIT AGAIN: 再次编辑:

So here is the method that is supposed to list everything. 因此,这里是应该列出所有内容的方法。

    public void listAll()
{
    for(int x = 0; x < employeeCount; x++)
        System.out.println(employees[x]);
}

thanks for your help! 谢谢你的帮助!

First Problem 第一个问题

You passed in int empType , then switched on employeeType 您传入int empType ,然后打开employeeType

Second Problem 第二个问题

You passed in int empType , but all of the cases in your switch are char , like case '1': . 您传递了int empType ,但您的开关中的所有情况都是char ,例如case '1': int empType

Edit: You edited your question to fix some of the problems >:-/ 编辑:您已编辑问题,以解决某些问题>:-/

Third Problem 第三个问题

In your listAll() method, you are attempting to print an object that has no toString() method. 在您的listAll()方法中,您试图打印不具有toString()方法的对象。 Give your abstract Employee class a toString() method like the following. 给您的抽象Employee类一个toString()方法,如下所示。

public String toString() {
    return lastName + ", " + firstName + " " + middleInitial;
}

Now, imagine you want your child classes to have a more detailed representation like " Smith, John C. is hourly. " You can do this by adding ANOTHER toString method to each of your children classes, but you get to reuse the part you already wrote! 现在,假设您希望子类具有更详细的表示形式,例如“ Smith,John C.每小时。 ”您可以通过向每个子类中添加ANOTHER toString方法来做到这一点,但是您必须重用已经存在的部分写了! For example, this would go in your hourly employee class. 例如,这将在您的每小时员工班级中进行。

public String toString() {
    return super.toString() + " is hourly.";
}

Several things come to mind but most of them regard the overall design and not your specific question. 我想到了几件事情,但其中大多数都考虑了总体设计,而不是您的特定问题。

Off By One 一对一

The way your code looks at the moment it contains an off by one error . 您的代码当前包含一个错误的外观。 You're initializing employeeCount to 0 but you're incrementing it to 1 before the first insert. 您正在将employeeCount初始化为0但是在第一次插入之前将其递增为1 Hence the first employee goes into the second array slot at employees[1] . 因此, 第一名员工进入了employees[1]第二个阵列插槽。

But your output loop is correct and after the first insert, it only outputs employees[0] , which is still null . 但是您的输出循环是正确的,并且在第一次插入之后,它仅输出employees[0] ,该值仍然为null Just move the employeeCount += 1; 只需移动employeeCount += 1; to the end of the method and you're fine. 到方法的结尾,您就可以了。

(In case that isn't clear: Java counts array indices from 0 to length-1 .) (在不清楚的情况下:Java计算从0length-1数组索引。)

IndexOutOfBounds IndexOutOfBounds

There's another bug. 还有另一个错误。 You're comparing employeeCount > EMPLOYEES_MAX . 您正在比较employeeCount > EMPLOYEES_MAX If employeeCount = EMPLOYEES_MAX , it passes the test but inserting at employees[EMPLOYEES_MAX] will fail because it is out of the array's bounds. 如果employeeCount = EMPLOYEES_MAX ,则它通过了测试,但是在employees[EMPLOYEES_MAX]处插入将失败,因为它超出了数组的范围。

You ave to check for employeeCount >= EMPLOYEES_MAX . 您必须检查employeeCount >= EMPLOYEES_MAX This might seem counter intuitive because in your method you used it as "number of employees after this insert" . 这似乎很违反直觉,因为在您的方法中,您将其用作“此插入之后的员工数” If you include my correction from above, the interpretation is "number of employees already inserted" . 如果从上方包括我的更正,则解释为“已插入的员工数”

case '1'更改为case 1 ,依此类推,当您传入int时,显然不想打开char值。

I have joined what you have written until now and looks that it works (constants introduced for code readability): 到目前为止,我已经加入了您所写的内容,并且看起来行之有效(为提高代码可读性而引入了常量):

public class EmployeeList {

public static final int EMP_TYPE_HOURLY = 1;
public static final int EMP_TYPE_SALARY = 2;
public static final int EMP_TYPE_COMMISSION = 3;
public static final char EMP_GEN_MALE = 'M';
public static final char EMP_GEN_FEMALE = 'F';

private int employeeCount = 0;
private static final int EMPLOYEES_MAX = 5;
private Employee[] employees = new Employee[EMPLOYEES_MAX];

public boolean addEmployee(int empType, String first, String last, char mi, char gen, int empNum, boolean full, double amount) {
    employeeCount += 1;

    if (employeeCount > EMPLOYEES_MAX) {
        System.out.println("ERROR: ARRAY FULL. UNABLE TO ADD NEW EMPLOYEE");
        return false;
    } else {
        switch (empType) {
            case EMP_TYPE_HOURLY:
                employees[employeeCount] = new HourlyEmployee(first, last, mi, gen, empNum, full, amount);
                break;

            case EMP_TYPE_SALARY:
                employees[employeeCount] = new SalaryEmployee(first, last, mi, gen, empNum, full, amount);
                break;

            case EMP_TYPE_COMMISSION:
                employees[employeeCount] = new CommissionEmployee(first, last, mi, gen, empNum, full, amount);
                break;
        }
        return true;
    }
}

public Employee[] getEmployees() {
    return employees;
}

public static void main(String[] args) {
    EmployeeList empList = new EmployeeList();

    empList.addEmployee(EMP_TYPE_HOURLY, null, null, 'A', EMP_GEN_MALE, 555, true, 100.0);
    empList.addEmployee(EMP_TYPE_HOURLY, null, null, 'A', EMP_GEN_FEMALE, 555, true, 100.0);
    empList.addEmployee(EMP_TYPE_SALARY, null, null, 'A', EMP_GEN_FEMALE, 555, true, 100.0);
    empList.addEmployee(EMP_TYPE_COMMISSION, null, null, 'A', EMP_GEN_FEMALE, 555, true, 100.0);

    for (int i = 0; i < EMPLOYEES_MAX; i++) {
        System.out.println("" + empList.getEmployees()[i]);
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM