Java 当我';我试图从另一个类向引用的类添加一些值
我是c#程序员,我已经习惯了c#的语法用于封装和其他东西。但是现在,由于一些原因,我应该用java写一些东西,我现在正在练习java一天!为了让自己更熟悉java的oop概念,我将为自己创建一个虚拟项目 我想做的是,我想要一个名为“Employee”的类,它有三个属性(字段):Java 当我';我试图从另一个类向引用的类添加一些值,java,nullpointerexception,Java,Nullpointerexception,我是c#程序员,我已经习惯了c#的语法用于封装和其他东西。但是现在,由于一些原因,我应该用java写一些东西,我现在正在练习java一天!为了让自己更熟悉java的oop概念,我将为自己创建一个虚拟项目 我想做的是,我想要一个名为“Employee”的类,它有三个属性(字段):firstName,lastName,和id。然后我想创建另一个名为EmployeeArray的类,它将在自身内部构造一个Employee数组,并可以对其执行一些操作(出于某些原因,我希望这个项目是这样!!) 现在,我想在
firstName
,lastName
,和id
。然后我想创建另一个名为EmployeeArray
的类,它将在自身内部构造一个Employee
数组,并可以对其执行一些操作(出于某些原因,我希望这个项目是这样!!)
现在,我想在EmployeeArray
类中为Employee
s添加一些值。以下是我目前的工作:
//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();
employee[numOfItems].SetValues(firstName, lastName, id);
numOfItems++;
}
catch (Exception e) {
e.printStackTrace();
}
}
请粘贴错误的堆栈跟踪。更改此行:
System.out.println(e.toString())代码>到e.printStackTrace()你可以自己调试原因。哦,是的!现在我看到了!!我不知道为什么我要在EmployeeArray
的构造函数中创建Employee
的引用!!!谢谢
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();
}
}