-1

I am getting a java.lang.NullPointerException error for my calculateTotalPay method and calculateAveragePay method. The error message states that it cannot read the array length because this.weeklyHours is null.

public double calculateAveragePay() {
  double averagePay = 0;
  double totalPay = 0;
 // totalPay = calculateTotalPay();

  averagePay = totalPay / weeklyHours.length;
  return averagePay;
}

public double calculateTotalPay() {
  int totalAmount = 0;
 // for (int index = 0; index < weeklyHours.length; index++)
    totalAmount += weeklyHours[index];
  return totalAmount;
} 
public class Employee {
    private static final int DEFAULT_WEEKS = 52;
    private String name;
    private double salary;
    private double[] weeklyHours;
    //private int numWeeks;

    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
        double[] weeklyHours = new double[DEFAULT_WEEKS];
    }

    public Employee(String name, double salary, int numWeeks) {
        this.name = name;
        this.salary = salary;
        double[] weeklyHours = new double[numWeeks];
    }
John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

2

You have the same bug in both constructors. You are shadowing the field with a new local variable. Use this like you did with the other fields to avoid this class of error.

public Employee(String name, double salary) {
    this.name = name;
    this.salary = salary;
    // double[] weeklyHours = new double[DEFAULT_WEEKS];
    this.weeklyHours = new double[DEFAULT_WEEKS];
}

public Employee(String name, double salary, int numWeeks) {
    this.name = name;
    this.salary = salary;
    // double[] weeklyHours = new double[numWeeks];
    this.weeklyHours = new double[numWeeks];
}

You could replace the first constructor with

public Employee(String name, double salary) {
    this(name, salary, DEFAULT_WEEKS);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

From within the Employee class constructor methods, you're initializing a local variable, as opposed to assigning the class variable.

double[] weeklyHours = new double[DEFAULT_WEEKS];
double[] weeklyHours = new double[numWeeks];

Just remove the declaration type, to access the class variable.

weeklyHours = new double[DEFAULT_WEEKS];
weeklyHours = new double[numWeeks];
Reilas
  • 3,297
  • 2
  • 4
  • 17