java编写一个最简单的 2 层楼的电梯管理模拟实验,假定电梯容纳 1 人,先来
时间: 2024-01-22 20:21:02 浏览: 22
好的,以下是一个简单的 Java 代码实现:
```java
import java.util.Scanner;
public class ElevatorSimulation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int currentFloor = 1; // 当前楼层
int targetFloor = 1; // 目标楼层
String direction = ""; // 电梯运行方向
boolean isRunning = false; // 电梯是否运行
// 开始模拟
while (true) {
System.out.print("请输入当前楼层(1-2):");
currentFloor = scanner.nextInt();
if (currentFloor < 1 || currentFloor > 2) {
System.out.println("输入不合法,请重新输入!");
continue;
}
System.out.print("请输入目标楼层(1-2):");
targetFloor = scanner.nextInt();
if (targetFloor < 1 || targetFloor > 2) {
System.out.println("输入不合法,请重新输入!");
continue;
}
// 判断电梯运行方向
if (currentFloor < targetFloor) {
direction = "上";
} else if (currentFloor > targetFloor) {
direction = "下";
} else {
direction = "";
}
System.out.println("电梯正在" + direction + "行!");
isRunning = true;
// 模拟电梯运行
while (isRunning) {
if (currentFloor < targetFloor) {
currentFloor++;
System.out.println("电梯到达" + currentFloor + "楼!");
} else if (currentFloor > targetFloor) {
currentFloor--;
System.out.println("电梯到达" + currentFloor + "楼!");
} else {
System.out.println("电梯到达目的地!");
isRunning = false;
}
}
System.out.print("是否继续模拟(y/n)?");
String choice = scanner.next();
if (choice.equalsIgnoreCase("n")) {
break;
}
}
System.out.println("模拟结束!");
}
}
```
这个程序实现了一个最简单的 2 层楼的电梯管理模拟实验,用户可以输入当前楼层和目标楼层,程序会计算出电梯运行方向,并模拟电梯的运行过程。用户可以选择继续模拟或退出程序。