1. 程式人生 > >Java使用棧和佇列模擬停車場問題

Java使用棧和佇列模擬停車場問題

停車場管理:

本題為計算機系專業課資料結構實驗

[問題描述]

設停車場是一個可以停放n輛汽車的狹長通道,且只有一個大門可供汽車進出。汽車在停車場內按車輛到達時間的先後順序,依次有北向南排列(大門在最南端,最先到達的第一車停放在車場的最北端),若車場內已停滿n輛車,那麼後來的車只能在門外的便道上等候,一旦有車開走,則排在便道上的第一輛車即可開入;當停車場內某輛車要離開時,在它之後進入的車輛必須先退出車場為它讓路,待該輛車開出大門外,其他車輛再按原次序進入車場,每輛停放在車場的車在它離開停車場時必須按它停留的時間長短交納費用。試為停車場編制按上述要求進行管理的模擬程式。
[實現提示]
以棧模擬停車場,以佇列模擬車場外的便道。每一組輸入資料包括三個資料項:汽車“到達”或“離去”資訊、汽車牌照號碼以及到達或離去的時刻。對每一組輸入資料進行操作後的輸出資訊為:若是車輛到達,則輸出汽車在停車場內或便道上的停車位置;若是車輛離去,則輸出汽車在停車場內停留的時間和應交納的費用(在便道上停車不收費)。棧以順序儲存結構實現,佇列以連結串列結構實現。

 

實現:

 

車輛類:

package test2;

/**
 * 汽車
 * @author Xu Yiqing
 *
 */
public class Car {
    String id;
    private long reachTime;
    private long leaveTime;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    
public long getReachTime() { return reachTime; } public void setReachTime(long reachTime) { this.reachTime = reachTime; } public long getLeaveTime() { return leaveTime; } public void setLeaveTime(long leaveTime) { this.leaveTime = leaveTime; } }

 

 

停車場棧:

package test2;
/**
 * 停車場棧
 * @author Xu Yiqing
 *
 */
public class ParkingLod {
    private Car[] cars;
    private int top;
    private Integer maxSize;

    
    
    public Car[] getCars() {
        return cars;
    }

    public ParkingLod(int size) {
        if (size < 1) {
            throw new RuntimeException("請輸入正確的停車場大小");
        }
        this.cars = new Car[size];
        this.maxSize = size;
        this.top = -1;
    }

    public boolean isEmpty() {
        return top == -1 ;
    }
    public int getSize() {

        return top+1;
    }


    public boolean push(Car car) {
        if (this.top == this.maxSize - 1) {
            throw new RuntimeException("停車場已滿,無法停車");
        } else {
            this.cars[++top] = car;
            return true;
        }
    }

    public Car pop() {
        if (top == -1) {
            throw new RuntimeException("停車場為空");
        } else {
            return cars[top--];
        }
    }
    
    public boolean isFull(){
        return top==maxSize-1;
    }
    
    public Car getCar(String carId) {
        for(int i=0;i<this.getSize();i++) {
            if(carId.equals(cars[i].getId())) {
                return cars[i];
            }
        }
        return null;
    }

}

 

 

道路佇列:

package test2;
/**
 * 通道
 * @author Xu Yiqing
 *
 */
public class Path {
    private Car[] cars;
    private int maxSize=0; 
    private int front;  
    private int rear; 
    
    
    
    public Car[] getCars() {
        return cars;
    }

    public int getMaxSize() {
        return maxSize;
    }

    public int getFront() {
        return front;
    }

    public int getRear() {
        return rear;
    }

    public Path(int size){
        if(this.maxSize >=0){
            this.maxSize = size;
            this.cars = new Car[size];
            front = rear =0;
        }else{
            throw new RuntimeException("道路大小設定有誤");
        }
    }
    
    public boolean isEmpty(){
        return rear==front;
    }
    public boolean add(Car car){
        if(rear== maxSize){
            throw new RuntimeException("道路已滿,停不下車");
        }else{
            cars[rear++]=car;
            return true;
        }
    }
    
    public Car peek(){
        if(this.isEmpty()){
            throw new RuntimeException("道路異常");
        }else{
            return cars[front];
        }    
    }
    
    public Car poll(){
        if(this.isEmpty()){
            throw new RuntimeException("道路異常");
        }else{
            Car car = cars[front];  
            cars[front++] = null;                 
            return car;
        }            
    }
    
    public int length(){
        return rear-front;
    }
}

 

 

主程式:

package test2;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * 主類
 * @author Xu Yiqing
 *
 */
public class Main {

    private static JFrame frame = null;
    private static JTextArea resultText;
    private static JTextField carIdText;

    // 預設車庫能停10輛車,通道能停100輛車
    private static ParkingLod parkingLod = new ParkingLod(10);
    private static Path path = new Path(100);

    /**
     * 程式入口
     * @param args
     */
    public static void main(String[] args) {
        frame = new JFrame("Parking Lot 1.0");
        frame.setBounds(800, 300, 350, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        JPanel panel = new JPanel();
        panel.setBackground(Color.lightGray);
        frame.add(panel);
        placeComponents(panel);

        frame.setVisible(true);
    }

    /**
     * 圖形化介面
     * @param panel Panel
     */
    private static void placeComponents(JPanel panel) {
        panel.setLayout(null);

        JLabel carLabel = new JLabel("Car ID:");
        carLabel.setBounds(10, 20, 80, 25);
        panel.add(carLabel);

        carIdText = new JTextField(20);
        carIdText.setBounds(100, 20, 165, 25);
        panel.add(carIdText);

        JLabel resultLabel = new JLabel("Result:");
        resultLabel.setBounds(10, 150, 80, 50);
        panel.add(resultLabel);

        resultText = new JTextArea(5, 1);
        resultText.setEditable(false);
        resultText.setBounds(80, 130, 200, 100);
        resultText.setLineWrap(true);
        Font font1 = new Font("宋體", Font.BOLD, 15);
        resultText.setFont(font1);
        panel.add(resultText);

        JButton arriveButton = new JButton("Arrive");
        arriveButton.setBackground(Color.orange);
        arriveButton.setBounds(50, 50, 80, 25);
        panel.add(arriveButton);
        arriveButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                arrive();
            }
        });

        JLabel authorLabel = new JLabel("Author:許一清");
        Font font = new Font("宋體", Font.ITALIC, 15);
        authorLabel.setFont(font);
        authorLabel.setBounds(120, 230, 150, 25);
        panel.add(authorLabel);

        JButton leaveButton = new JButton("Leave");
        leaveButton.setBounds(200, 50, 80, 25);
        leaveButton.setBackground(Color.pink);
        panel.add(leaveButton);
        leaveButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                leave();
            }
        });

        JButton showButton = new JButton("Show");
        showButton.setBounds(50, 80, 80, 25);
        panel.add(showButton);
        showButton.setBackground(Color.green);
        showButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                show();
            }
        });

        JButton exitButton = new JButton("Exit");
        exitButton.setBounds(200, 80, 80, 25);
        panel.add(exitButton);
        exitButton.addActionListener(new ActionListener() {

            /**
             * 退出按鈕比較簡單
             */
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

    }

    /**
     * 展示按鈕
     */
    protected static void show() {
        resultText.setText("現在停車場有:" + parkingLod.getSize() + "輛車\n道路上有:" + path.length() + "輛車");
        carIdText.setText("");
    }

    /**
     * 離開按鈕
     */
    protected static void leave() {

        Car car = new Car();
        String id = carIdText.getText();

        if (id.isEmpty()) {
            resultText.setText("請輸入車牌號");
            return;
        } else {
            // 車庫不滿直接刪除車
            if (!parkingLod.isFull()) {
                Car[] cars;
                Car[] resultCars = new Car[parkingLod.getSize()];
                ParkingLod newParkingLod;
                car = parkingLod.getCar(id);
                if (car != null) {
                    resultText.setText("車輛:" + car.getId() + "\n離開了");
                    cars = parkingLod.getCars();
                    int index = 0;
                    for (int i = 0; i < parkingLod.getSize(); i++) {
                        if (!cars[i].getId().equals(id)) {
                            resultCars[index++] = cars[i];
                        }
                    }
                    newParkingLod = new ParkingLod(10);
                    for (int i = 0; i < index; i++) {
                        newParkingLod.push(resultCars[i]);
                    }
                    parkingLod = newParkingLod;
                } else {
                    resultText.setText("停車場不存在\n車輛:" + carIdText.getText());
                    return;
                }
            }
            // 車庫滿了通道新車進入
            else {

                Car[] cars;
                Car[] resultCars = new Car[parkingLod.getSize()];
                car = parkingLod.getCar(id);
                ParkingLod newParkingLod;
                if (car != null) {
                    car.setLeaveTime(System.currentTimeMillis());
                    long time = car.getLeaveTime() - car.getReachTime();
                    resultText.setText("車輛:" + car.getId() + "\n離開了\n停車時間:" + time + "毫秒");
                    cars = parkingLod.getCars();
                    int index = 0;
                    for (int i = 0; i < parkingLod.getSize(); i++) {
                        if (!cars[i].getId().equals(id)) {
                            resultCars[index++] = cars[i];
                        }
                    }
                    newParkingLod = new ParkingLod(10);
                    for (int i = 0; i < index; i++) {
                        newParkingLod.push(resultCars[i]);
                    }

                    if (!path.isEmpty()) {
                        Car temp = path.getCars()[path.getFront()];
                        newParkingLod.push(temp);
                        temp.setReachTime(System.currentTimeMillis());
                        path.poll();
                    }
                    parkingLod = newParkingLod;

                } else {
                    resultText.setText("停車場中不存在\n車輛:" + carIdText.getText());
                    return;
                }
            }
        }
    }

    /**
     * 到達按鈕
     */
    protected static void arrive() {
        Car car = new Car();
        String id = carIdText.getText();

        if (!id.isEmpty()) {

            car.setId(id);

            // 判斷停車場是否滿
            if (!parkingLod.isFull()) {
                car.setReachTime(System.currentTimeMillis());
                parkingLod.push(car);
                resultText.setText("車輛:" + id + "\n停車成功");
                carIdText.setText("");
            } else {
                path.add(car);
                resultText.setText("停車場滿了\n車輛:" + car.getId() + "\n停在道路上");
                carIdText.setText("");

            }
        } else {
            resultText.setText("請輸入車牌號");
            carIdText.setText("");
            return;

        }
    }
}