Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read the array length because "this.weeklyHours" is null

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];
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading