首页 > 解决方案 > 员工数据库使用员工对象数组但得到 NullPointerException

问题描述

我不明白在哪里编辑我的代码。我正在尝试使用 Employee 对象数组创建一个员工数据库。它在 Line24 处给出 java.lang.NullPointerException。请帮我理解。

package multipleEmployeeData;

import java.util.Scanner;

public class MultipleEmployeeData extends EmployeeDetail{
    static EmployeeDetail[] emp=null;


    public static void empDataoutput() {
        System.out.println("Employee Database: ");
        System.out.println("EmployeeName"+"\t"+"EmployeeNumber"+"\t"+"EmployeeSalary"+"\t"+"EmployeeMobileNumber");
        for(int i=0;i<3;i++ ) {
            System.out.print(emp[i].EmpName+"\t"+emp[i].EmpNumber+"\t"+emp[i].Salary+"\t"+emp[i].MobNumber);
            System.out.println();
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scn=new Scanner(System.in);
        emp=new EmployeeDetail[3];
        for(int i=0;i<3;i++) {
            System.out.println("Enter the employee "+(i+1)+" name");
            emp[i].EmpName=scn.nextLine();
            System.out.println("Enter the employee "+(i+1)+" number");
            emp[i].EmpNumber=Integer.parseInt(scn.nextLine());
            System.out.println("Enter the employee "+(i+1)+" Mobile number");
            emp[i].MobNumber=Long.parseLong(scn.nextLine());
            System.out.println("Enter the employee "+(i+1)+" Salary");
            emp[i].Salary=Float.parseFloat(scn.nextLine());
        }
        scn.close();

        empDataoutput();    
    }

}

class EmployeeDetail{
    String EmpName;
    int EmpNumber;
    Float Salary;
    Long MobNumber;
}

标签: javanullpointerexception

解决方案


更改如下代码:

public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner scn=new Scanner(System.in);
        emp=new EmployeeDetail[3];
        for(int i=0;i<3;i++) {
            emp[i] = new EmployeeDetail();
            System.out.println("Enter the employee "+(i+1)+" name");
            emp[i].EmpName=scn.nextLine();
            System.out.println("Enter the employee "+(i+1)+" number");
            emp[i].EmpNumber=Integer.parseInt(scn.nextLine());
            System.out.println("Enter the employee "+(i+1)+" Mobile number");
            emp[i].MobNumber=Long.parseLong(scn.nextLine());
            System.out.println("Enter the employee "+(i+1)+" Salary");
            emp[i].Salary=Float.parseFloat(scn.nextLine());
        }
        scn.close();

        empDataoutput();    
    }

查看emp[i] = new EmployeeDetail();对象在哪里实例化并添加到 emp 数组的索引。

emp=new EmployeeDetail[3];创建大小为 3 的 EmployeeDetail 数组,但其中包含null值。


推荐阅读