java - 员工数据库使用员工对象数组但得到 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;
}
解决方案
更改如下代码:
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
值。
推荐阅读
- c# - Linq.Select() 中的嵌套表达式方法调用
- r - R Plot 条形图转置数据框
- android - 如果未选择列表视图中的项目,如何更改列表视图中的背景颜色
- javascript - Microsoft Edge window.getSelection() 返回不正确的结果
- angular5 - 如何将当前位置的“纬度”和“经度”设置为“AgmCoreModule”
- python - 使用 python 将加速度计传感器的 x、y、z 值输出为 csv 格式
- java - 初始化后回收站列表适配器为空
- vtiger - Vtiger 7.1 活动目录
- node.js - mongodb:将上一个管道结果的数组引用到下一个管道中
- angularjs - 两个日期之间的差异 moment.js