javafx两层电梯模拟
时间: 2023-06-27 14:08:25 浏览: 55
这是一个比较复杂的问题,需要涉及到多个类和算法。以下是一个简单的实现示例:
首先,我们需要定义电梯类:
```java
public class Elevator {
private int currentFloor;
private int direction; // 1 for up, -1 for down
private boolean[] floorRequests;
public Elevator(int numFloors) {
currentFloor = 1;
direction = 1;
floorRequests = new boolean[numFloors + 1];
}
public int getCurrentFloor() {
return currentFloor;
}
public int getDirection() {
return direction;
}
public void setDirection(int direction) {
this.direction = direction;
}
public boolean[] getFloorRequests() {
return floorRequests;
}
public void requestFloor(int floor) {
floorRequests[floor] = true;
}
public void moveToNextFloor() {
currentFloor += direction;
}
}
```
然后,我们需要定义电梯控制类:
```java
public class ElevatorController {
private Elevator[] elevators;
private int numFloors;
public ElevatorController(int numElevators, int numFloors) {
elevators = new Elevator[numElevators];
for (int i = 0; i < numElevators; i++) {
elevators[i] = new Elevator(numFloors);
}
this.numFloors = numFloors;
}
public void requestElevator(int floor) {
// find the closest elevator and assign it to this floor request
int closestElevatorIndex = -1;
int minDistance = Integer.MAX_VALUE;
for (int i = 0; i < elevators.length; i++) {
int distance = Math.abs(elevators[i].getCurrentFloor() - floor);
if (distance < minDistance) {
closestElevatorIndex = i;
minDistance = distance;
}
}
elevators[closestElevatorIndex].requestFloor(floor);
}
public void step() {
// move the elevators one floor at a time
for (Elevator elevator : elevators) {
if (elevator.getFloorRequests()[elevator.getCurrentFloor()]) {
// stop at this floor and clear the request
elevator.getFloorRequests()[elevator.getCurrentFloor()] = false;
// TODO: open the doors and let people in/out
}
if (elevator.getCurrentFloor() == 1) {
elevator.setDirection(1); // change direction to up
} else if (elevator.getCurrentFloor() == numFloors) {
elevator.setDirection(-1); // change direction to down
} else if (elevator.getFloorRequests()[elevator.getCurrentFloor() + elevator.getDirection()]) {
// someone has requested the next floor in the current direction
// keep moving in that direction
} else {
// no more requests in the current direction, change direction
elevator.setDirection(-elevator.getDirection());
}
elevator.moveToNextFloor();
}
}
}
```
最后,我们需要一个主方法来模拟整个过程:
```java
public static void main(String[] args) {
ElevatorController controller = new ElevatorController(2, 10); // 2 elevators, 10 floors
controller.requestElevator(3);
controller.requestElevator(5);
controller.requestElevator(7);
while (true) {
controller.step();
try {
Thread.sleep(1000); // wait for 1 second between steps
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
这段代码会模拟电梯的运行过程,每秒钟调用一次 `step()` 方法。当有人请求某一层楼时,会分配最近的电梯来处理请求。当电梯到达某一层楼时,会停下来并打开门,等待乘客进出。如果没有请求,电梯会继续朝着当前方向移动,直到遇到新的请求或到达顶楼或底楼,然后会改变方向继续运行。