我正在使用工厂模式通过ElevatorMover
界面创建不同类型的电梯。工厂将电梯存储在ArrayList
个ElevatorMover
对象中。从ElevatorArrayList.get(i)
检索电梯[ArrayList
]时,无法调用PassengerElevator
方法。仅ElevatorMover
方法(当然不会实现)。
我在这里不能做什么?
这是我要在main中调用的代码
// make elevator 1 go to the 11th floor
testBuilding.getElevator(1).moveUp(11);
这是我的界面
public interface ElevatorMover {
public void moveUp(int i);
public void moveDown(int i);
public void openDoors();
这是PassengerElevator方法
@Override
public void moveUp(int i) {
while (currentFloor != i) {
setCurrentFloor(currentFloor++);
}
}
错误讯息
Exception in thread "main" java.lang.NullPointerException
at Elevator.Building.getElevator(Building.java:109)
at Elevator.ElevatorSimulatorMain.main(ElevatorSimulatorMain.java:34)
Building.class构造函数
private ArrayList<Floor> floorArrayList; // the ArrayList of floors in the building
private ArrayList<ElevatorMover> elevatorArrayList; // the ArrayList of elevators in the building
public Building(int numFloors, int numElevators) {
this.numFloors = numFloors;
this.numElevators = numElevators;
// create each floor
if (numFloors > 0) // Must have 1 or more floors
{
for (int i = 1; i <= numFloors; i++) {
floorArrayList.add(new Floor(i));
}
}
else
{
System.out.println("Building must have 1 or more floors.");
}
// create each elevator.
if (numElevators > 0) // Must have 1 or more elevators
{
for (int i = 1; i <= numElevators; i++) {
elevatorArrayList.add(ElevatorFactory.build("Passenger", i));
}
}
else
{
System.out.println("Building must have 1 or more elevators.");
}
}
ElevatorFactory的构建方法
public static ElevatorMover build(String type, int elevID) {
if (type.equals("Passenger")) {
return new PassengerElevator(elevID);
}
else return null; // don't know what this is
}
getElevator方法
public ElevatorMover getElevator(int i) {
return elevatorArrayList.get(i);
}
最佳答案
我猜你没有创建电梯。例List<ElevatorMover> elevatorArrayList = new ArrayList<ElevatorMover>();
private ArrayList<ElevatorMover> elevatorArrayList; // This is just declaring not creating elevatorArrayList