下面是我正在开发的应用程序:
这是 示例场景:
1) For the given hierarchy:
Manager A $300
Manager B $300
Developer $1000
QA Tester $500
2) Manager A’s allocation should be: $2100
我目前遇到的问题是当我运行代码时出现以下错误:
Exception in thread "main" java.lang.NullPointerException
at expenseApp.Manager.add(Manager.java:28)
at main.MainClass.main(MainClass.java:15)
我对发生了什么以及如何解决这个问题感到困惑。能否请你帮忙?我对编程比较陌生,所以建议的例子对我有很大帮助。在管理器中,我留下了一些注释掉的代码,代表了我尝试修复的一些代码。
谢谢。
package main;
import expenseApp.Developer;
import expenseApp.Manager;
import expenseApp.QATester;
public class MainClass {
public static void main(String[] args)
{
QATester tester1 = new QATester();
Developer dev1 = new Developer();
Manager managerB = new Manager();
**managerB.add(tester1);**
managerB.add(dev1);
Manager managerA = new Manager();
managerA.add(managerB);
}
}
package expenseApp;
public abstract class Employee
{
public abstract int getExpenses();
}
package expenseApp;
import java.util.ArrayList;
public class Manager extends Employee
{
private ArrayList<Manager> managerList; //= new ArrayList<>();
private ArrayList<Employee> employeeList; //= new ArrayList<>();
// public Manager(ArrayList<Manager> managers, ArrayList<Employee> employees)
// {
// this.managerList = new ArrayList<>(managers);
// this.employeeList = new ArrayList<>(employees);
// }
public void add(Employee employee)
{
if(employee instanceof Manager)
{
//managerList = new ArrayList<>();
managerList.add((Manager) employee);
}
else
{
//employeeList = new ArrayList<>();
**employeeList.add(employee);**
}
}
@Override
public int getExpenses()
{
return 300;
}
public int getTotalExpenses()
{
int totalExpenses = 0;
for(Manager manager : managerList)
{
totalExpenses += manager.getTotalExpenses();
}
for(Employee employee : employeeList)
{
totalExpenses += employee.getExpenses();
}
return totalExpenses;
}
}
package expenseApp;
public class QATester extends Employee
{
@Override
public int getExpenses()
{
return 500;
}
}
package expenseApp;
public class Developer extends Employee
{
@Override
public int getExpenses()
{
return 1000;
}
}
答案 0 :(得分:1)
您可以使用代码初始化注释掉的成员变量,例如
private ArrayList<Manager> managerList; //= new ArrayList<>();
private ArrayList<Employee> employeeList; //= new ArrayList<>();
尝试:
private ArrayList<Manager> managerList = new ArrayList<>();
private ArrayList<Employee> employeeList = new ArrayList<>();
答案 1 :(得分:1)
那是因为您的列表未初始化。
private ArrayList<Manager> managerList; //= new ArrayList<>();
您正在尝试:
managerList.add((Manager) employee);
在列表的null实例上,实例变量默认初始化为null。
同样适用于employeeList
。