sách gpt4 ai đã đi

java - 当我尝试从另一个类向引用的类添加一些值时,出现 nullPointerException

In lại 作者:行者123 更新时间:2023-12-02 06:39:12 29 4
mua khóa gpt4 Nike

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

我想做的是,我想要一个名为“Employee”的类,它具有三个属性(字段):firstName , lastName ,和nhận dạng然后我想创建另一个名为 EmployeeArray 的类这将构造一个 Người lao động 的数组s 在其内部并且可以对其执行一些操作(由于某些原因我希望这个项目以这种方式!!)现在我想向 Người lao động 添加一些值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){
thử {
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 中引用。我不知道我错过了什么。有什么建议吗?

1 Câu trả lời

"I am c# programmer and I am used to c#'s syntaxes for encapsulation and other stuff."

好。那么您应该对 Java 感到非常熟悉:)。

"The problem is I get a nullPointerException when the app wants to set the values".

在 C# 中,如果您有一个对象数组,那么您必须首先分配该数组...然后您需要“新建”放入该数组中的任何对象。不是吗?

Java 中也是如此:)

建议更改:

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

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

3)更改您的“插入”方法:

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

关于java - 当我尝试从另一个类向引用的类添加一些值时,出现 nullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19331220/

29 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com