import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
/**
* @author csk
*/
public class ParkingLot {
class Car {
/**
* licence:牌照,如:'TUE-87B'
* moveTimes:移动次数
*/
String licence;
int moveTimes;
Car(String licence) {
this.licence = licence;
this.moveTimes = 0;
}
String getLicence() {
return licence;
}
int getMoveTimes() {
return moveTimes;
}
void moveCar() {
moveTimes++;
}
}
public static void main(String[] args) throws IOException {
new ParkingLot().parkingLotSimulation();
}
void parkingLotSimulation() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
StringBuilder sb = new StringBuilder();
String s;
//stack1模拟停车场
Stack<Car> stack1 = new Stack<>();
//最大停车位数 (从data.txt可以得知为5,数出来的)
int maxNumber = 5;
int count = 0;
while ((s = br.readLine()) != null) {
String[] array = s.split(" ");
//车辆停入功能的实现
if ("arrives".equals(array[1])) {
count++;
//最大停车数为5,超过则拒绝停入
if (count > maxNumber) {
System.out.println("Sorry " + array[0] + ", the lot is full");
count--;
continue;
}
Car newCar = new Car(array[0]);
//车停入
stack1.push(newCar);
}
//车辆开出功能的实现
//Stack2用来存放暂时挪出停车场的车辆
Stack<Car> stack2 = new Stack<>();
//若栈顶的车辆不是要出去的车辆,则将出去车辆前的所有车辆移出并存入stack2
if ("departs".equals(array[1])) {
try {
while (!stack1.peek().getLicence().equals(array[0])) {
stack1.peek().moveCar();
stack2.push(stack1.peek());
stack1.pop();
}
if (stack1.peek().getLicence().equals(array[0])) {
System.out.println(stack1.peek().getLicence() + " was moved " + stack1.peek().getMoveTimes() + " times while it was here");
stack1.pop();
count--;
while (!stack2.empty()) {
//待要出去的车辆移出后,还要将stack2暂存的车辆再重新移入停车场(即stack1)
stack1.push(stack2.peek());
stack2.pop();
}
}
}catch (Exception e){
System.out.println("Illegal input file!");
};
}
}
//停车场剩余车辆未出车辆,输入移动次数
while (!stack1.empty()) {
System.out.println(stack1.peek().getLicence() + " was moved "
+ stack1.peek().getMoveTimes() + " times while it was here");
stack1.pop();
}
br.close();
}
}
使用了java