为什么会出现NullPointerException?

public class Exercise8_4_v2 {
    static void sort(Employee[] employee,int n){
        double MaxId=0;
        double currentMax=0;

        for (int i = 0; i < n; i++) {
            currentMax=employee[i].WeeklyHours;
            for (int j = i+1 ; j < n ; j++) {
                if(employee[j].WeeklyHours >= currentMax){
                    currentMax = employee[j].WeeklyHours;
                    MaxId=j;
                }
            }
            System.out.println("Employee"+MaxId+" : "+currentMax);
        }
    }
    public static void main(String[] args) {

        double[][] workHours = {
                {2, 4, 3, 4, 5, 8, 8},
                {7, 3, 4, 3, 3, 4, 4},
                {3, 3, 4, 3, 3, 2, 2},
                {9, 3, 4, 7, 3, 4, 1},
                {3, 5, 4, 3, 6, 3, 8},
                {3, 4, 4, 6, 3, 4, 4},
                {3, 7, 4, 8, 3, 8, 4},
                {6, 3, 5, 9, 2, 7, 9}};

        Employee[] employee=new Employee[8] ;
        for (int i = 0; i < employee.length ; i++) {
           for (int j = 0; j < employee[i].Hours.length; j++) {
               employee[i].Hours[j]=workHours[i][j];
           }
           employee[i].WeeklyHours=employee[i].getWeeklyHours();

        }
        sort(employee, employee.length);


    }

}

class Employee {

    double[] Hours = new double[7];
    double WeeklyHours = 0;

    double getWeeklyHours() {

        for (int i = 0; i < 7; i++) {
            WeeklyHours += Hours[i];
        }
        return WeeklyHours;


    }
}

出现问题:Exception in thread "main" java.lang.NullPointerException
                  at ch09.Exercise8_4_v2.main(Exercise8_4_v2.java:33)

 

不知道问题错在哪里

 

在30行,for循环前面加上该循环语句就可以了,因为你是创建了数组中的8个元素,但并没有对元素初始化,也就是Employee对象是不存在。

for(int i=0;i<8;i++) {
       employee[i] = new Employee();
}

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

31行: employee[i]是null