我是 c# 程序员,我习惯了 c# 的封装和其他东西的语法。但是现在,由于某些原因,我应该用 java 写一些东西,我现在正在练习 java 一天!我要创建一个虚拟项目我的自我,以便让自己更熟悉 java 的 oop 概念
我想要做的是我想要一个名为“Employee”的类,它具有三个属性(字段):firstName
、、lastName
和id
。然后我想创建另一个名为的类EmployeeArray
,它将Employee
在自身内部构造一个 s 数组并可以执行一些对其进行操作(出于某些原因,我希望以这种方式进行此项目!!)现在我想为类中的Employee
s添加一些值。EmployeeArray
到目前为止,这是我的工作:
//this is the class for Employee
public class Employee {
private String firstName;
private String lastName;
private int id;
public void SetValues(String firstName, String lastName, int id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
//this is the EmployeeArray class
public class EmployeeArray {
private int numOfItems;
private Employee[] employee;
public EmployeeArray(int maxNumOfEmployees) {
employee = new Employee[maxNumOfEmployees];
numOfItems = 0;
}
public void InsertNewEmployee(String firstName, String lastName, int id){
try {
employee[numOfItems].SetValues(firstName, lastName, id);
numOfItems++;
}
catch (Exception e) {
System.out.println(e.toString());
}
}
//and this is the app's main method
Scanner input = new Scanner(System.in);
EmployeeArray employeeArray;
employeeArray = new EmployeeArray(input.nextInt());
String firstName;
String lastName;
int id;
firstName = input.nextLine();
lastName = input.nextLine();
id = input.nextInt();
employeeArray.InsertNewEmployee(firstName, lastName, id);
问题是当应用程序想要设置值时我得到一个 nullPointerException,它发生在employeeArray
参考中。我不知道我错过了什么。有什么建议吗?