Java实现模拟电梯上下楼
电梯需求
基于Java控制台模拟电梯上下楼
- 电梯先随机停在一个楼层 有人按下按钮 电梯判断几楼按的去接人,人进入电梯按下几楼 电梯判断送人
代码部分
// An highlighted block
import java.util.Random;
import java.util.Scanner;
/**
* @author
* @desc 基于Java控制台模拟电梯上下楼
* 电梯先随机停在一个楼层 有人按下按钮 电梯判断几楼按的去接人,人进入电梯按下几楼 电梯判断送人
* @env JDK 1.8
* @version 1.0
*/
public class LiftUpAndDown {
public final static Scanner sc=new Scanner(System.in);
public static void main(String[] args) throws InterruptedException {
//随机设置电梯所处楼层
Random random=new Random();
//初始化电梯所在位置
int source = random.nextInt(5)+1;
while(true){
//展示菜单
menu(source);
//获取键盘录入对象,模拟用户找寻电梯
int arrive = sc.nextInt();
//合理判断电梯运送范围
if(arrive>0&&arrive<=6){
System.out.println(arrive+"层有用户要使用电梯");
//模拟电梯接人
calculate(source,arrive);
//当前电梯所在位置
source=arrive;
//获取键盘录入对象,模拟电梯送人
System.out.println("请输入您将要到达几层,0表示取消使用");
int arrivePeople = sc.nextInt();
if (arrivePeople==0) break;//输入0时表示取消使用
//电梯送人
calculate2(source,arrivePeople);
//更新电梯所在位置
source=arrivePeople;
}
}
}
public static void calculate(int source, int arrive) throws InterruptedException {
if(source>arrive){// 6 4
System.out.println("电梯正在下降");
for(int index1=source;index1>=arrive;index1--){
if(index1==arrive){
System.out.println("电梯已到达"+index1+"层请乘坐");
break;
}
System.out.println("电梯到达"+index1+"层");
Thread.sleep(1000);
}
}else if(source<arrive){//4 6
System.out.println("电梯正在上升");
for(int index2=source;index2<=arrive;index2++){
if(index2==arrive){
System.out.println("电梯已到达"+index2+"层请乘坐");
break;
}
System.out.println("电梯到达"+index2+"层");
Thread.sleep(1000);
}
}else {
System.out.println("电梯已到达,请乘坐");
}
}
public static int calculate2(int source, int arrive) throws InterruptedException {
if(source>arrive){// 6 4
System.out.println("电梯正在下降");
for(int index1=source;index1>=arrive;index1--){
if(index1==arrive){
System.out.println("已到达");
break;
}
System.out.println("电梯到达"+index1+"层");
Thread.sleep(1000);
}
}else if(source<arrive){//4 6
System.out.println("电梯正在上升");
for(int index2=source;index2<=arrive;index2++){
if(index2==arrive){
System.out.println("已到达");
break;
}
System.out.println("电梯到达"+index2+"层");
Thread.sleep(1000);
}
}else {
System.out.println("电梯已到达");
}
return source;
}
public static void menu(int stay_in_floor){
System.out.println("****************欢迎使用电梯****************");
System.out.println("*******电梯共6层");
System.out.println("*******电梯当前正处于"+stay_in_floor+"层");
System.out.println("****************欢迎使用电梯****************");
}
}