繁体   English   中英

当我尝试将一些值添加到另一个类的引用类时,我得到一个nullPointerException

[英]I get a nullPointerException when I'm trying to add some values to a referenced class from another class

我是c#程序员,我习惯于c#的封装和其他东西的语法。但是现在,由于某些原因,我应该用java写一些东西,我现在正在练习java一天!我要创建一个虚拟项目我的自我,以使自己更熟悉java的oop概念

我想要做的是我想要一个名为'Employee'的类,它有三个属性(字段): firstNamelastNameid 。然后我想创建另一个名为EmployeeArray类,它将构建一个Employee的数组本身并且可以对它执行一些操作(出于某些原因,我希望这个项目以这种方式!!)现在我想在Employee中向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引用中。我不知道我错过了什么。有什么建议吗?

“我是c#程序员,我已经习惯了c#的封装和其他东西的语法。”

好。 然后你应该感觉到家里有Java :)。

“问题是,当应用程序想要设置值时,我得到一个nullPointerException”。

在C#中,如果你有对象的数组,那么您必须先分配数组...然后你需要“新”,你的阵列中把任何物体。 不是吗?

在Java中相同:)

建议的变化:

1)丢失“SetNewValues()”函数。

2)确保“Employee”有一个接受名字,姓氏和id的构造函数。

3)更改“插入”方法:

public void InsertNewEmployee(String firstName, String lastName, int id){
    try {
        employee[numOfItems] = new Employee(firstName, lastName, id);
        numOfItems++;
    }
    catch (Exception e) {
        System.out.println(e.toString());
    }

你没有制作员工对象

做这个:

public void InsertNewEmployee(String firstName, String lastName, int id){
try {
    employee[numOfItems]=new Employee();
    employee[numOfItems].SetValues(firstName, lastName, id);
    numOfItems++;
}
catch (Exception e) {
    e.printStackTrace();
}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM