核心功能类
package com. daiju;
import java. util. Collections;
import java. util. HashSet;
import java. util. Random;
import java. util. Scanner;
import java. util. Set;
public class Main {
public static final int MAX_WEIGHT = 1000 ;
public static final int MAX_FLOOR = 12 ;
public static final int MIN_FLOOR = 1 ;
public int currentFloor = 1 ;
public boolean up = true ;
public int randomWeight ( ) {
Random random = new Random ( ) ;
return random. nextInt ( 1441 ) + 60 ;
}
public boolean checkWeight ( int currentWeiht) {
return MAX_WEIGHT>= currentWeiht;
}
public Set< Integer> floors ( ) {
Scanner input = new Scanner ( System. in) ;
System. out. println ( "请输入楼层,多楼层之间用空格隔开,回车键结束输入!!!" ) ;
String str = input. nextLine ( ) ;
String[ ] nums = str. split ( " " ) ;
Set< Integer> finalNums = new HashSet ( ) ;
for ( int i= 0 ; i<= nums. length- 1 ; i++ ) {
if ( ! nums[ i] . equals ( currentFloor) ) {
finalNums. add ( Integer. parseInt ( nums[ i] ) ) ;
}
}
if ( Collections. max ( finalNums) > MAX_FLOOR || Collections. min ( finalNums) < MIN_FLOOR) {
System. out. println ( "输入的电梯楼层有误,请重新输入" ) ;
return floors ( ) ;
}
return finalNums;
}
public void beforeRun ( ) {
if ( checkWeight ( randomWeight ( ) ) ) {
System. out. println ( "关门,当前楼层:" + currentFloor) ;
} else {
System. out. println ( "超重!!!关门,当前楼层:" + currentFloor) ;
}
}
public void goFloor ( Set< Integer> floors, int currentFloor) throws Exception{
System. out. println ( "当前楼层:" + currentFloor) ;
Thread. sleep ( 1500 ) ;
if ( floors. contains ( currentFloor) ) {
System. out. println ( "到达楼层:" + currentFloor+ " 开门" ) ;
floors. remove ( currentFloor) ;
beforeRun ( ) ;
Thread. sleep ( 1500 ) ;
}
}
public void runFunction ( Set< Integer> floors, int flag) throws Exception{
if ( up&& floors. size ( ) > 0 ) {
if ( flag== 0 ) {
beforeRun ( ) ;
}
while ( floors. size ( ) > 0 && Collections. max ( floors) > currentFloor) {
currentFloor++ ;
goFloor ( floors, currentFloor) ;
}
up = false ;
runFunction ( floors, 1 ) ;
}
if ( ! up&& floors. size ( ) > 0 ) {
if ( flag== 0 ) {
beforeRun ( ) ;
}
while ( floors. size ( ) > 0 && Collections. max ( floors) < currentFloor) {
currentFloor-- ;
goFloor ( floors, currentFloor) ;
}
up = true ;
runFunction ( floors, 1 ) ;
}
}
}
测试类
package com. daiju;
public class Test {
public static void main ( String[ ] args) {
Main main = new Main ( ) ;
try {
while ( true ) {
main. runFunction ( main. floors ( ) , 0 ) ;
}
} catch ( Exception e) {
e. printStackTrace ( ) ;
}
}
}