gpt4 book ai didi

java - 工厂模式/ArrayList/接口(interface)问题

转载 作者:行者123 更新时间:2023-12-01 11:56:19 25 4
gpt4 key购买 nike

我正在使用工厂模式通过 ElevatorMover 接口(interface)创建不同类型的电梯。工厂将电梯存储在 ElevatorMover 对象的 ArrayList 中。当我从 ArrayList 检索电梯 [ElevatorArrayList.get(i)] 时,我无法调用 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);
}

最佳答案

我猜你没有创建elevatorArrayList。示例

List<ElevatorMover> elevatorArrayList = new ArrayList<ElevatorMover>();

private ArrayList<ElevatorMover> elevatorArrayList; // This is just declaring not creating elevatorArrayList

关于java - 工厂模式/ArrayList/接口(interface)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28422721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com