简体   繁体   中英

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). All three of the sub-classes extend the Employee class, which is abstract.

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.

Any help would be greatly appreciated, thank you all so much!

EDIT:

Ok, heres where my Employee array is initialized.

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. 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. Hourly
  2. Salary
  3. Commission Enter Choice: 1

Enter Last Name: Doe

Enter First Name: Jane

Enter Middle Initial: M

Enter Gender: F

Enter Employee Number: 1

Full Time? (y/n): y

Enter wage: 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. but instead just returns 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

Second Problem

You passed in int empType , but all of the cases in your switch are char , like case '1': .

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. Give your abstract Employee class a toString() method like the following.

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! 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. Hence the first employee goes into the second array slot at employees[1] .

But your output loop is correct and after the first insert, it only outputs employees[0] , which is still null . Just move the 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 .)

IndexOutOfBounds

There's another bug. You're comparing 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.

You ave to check for 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]);
    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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