簡體   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