The analysis of project robot rat

來源:互聯網
上載者:User
東搞搞西搞搞都1點過了,晚上很安靜的環境中帶上耳機聽HALO的OST音樂很棒的...
最近在看關於JAVA語言特性很爽的一本書:Java For Artists: The Art, Philosophy, and Science of Object-Oriented Programming  這本書裡的例子挺有意思的帖出來供初學者參考.

BufferedReader console = new BufferedReader(new InputStreamReader(System.in));讓有輸入的功能
String類裡有個方法charAt(int n) 是用於得到字串裡的第n個字元的.
Integer類裡有個方法parseInt(String) 是用於把字元轉換成整型數的
以上2個類都在java.lang包裡面
OK,忘下面看吧:

/* *******************************************************************
 Class:   IST 149
 Project: Robot Rat
 Student: Rick Miller
 ******************************************************************* */

import java.io.*;

/**
 * @author <b> Rick Miller </b>
 * @version 1.0
 *
 */
class RobotRat {
    // 私人的成員變數

    private BufferedReader console = null;

    private int pen_position = 0;

    private int direction = 0;

    private boolean floor[][] = null;

    private int current_row = 0;

    private int current_col = 0;

    // 類的靜態常量

    private static final int NORTH = 0;

    private static final int SOUTH = 1;

    private static final int EAST = 2;

    private static final int WEST = 3;

    private static final int UP = 0;

    private static final int DOWN = 1;

    /**
     * 建構函式
     * rows的個數決定floor數組的行
     * cols的個數決定floor數組的列
     */
    public RobotRat(int rows, int cols) {
        //初始化成員變數
        console = new BufferedReader(new InputStreamReader(System.in));
        direction = EAST;
        pen_position = UP;
        current_row = 0;
        current_col = 0;
        floor = new boolean[rows][cols];
        initializeFloor();
    }

    /**
     * 初始化每一個floor數組的變數為false
     */
    private void initializeFloor() {
        for (int i = 0; i < floor.length; i++) {
            for (int j = 0; j < floor[i].length; j++) {
                floor[i][j] = false;
            }
        }
    }

    /**
     * 重複顯示整個程式的操作介面
     * 處理使用者的輸入.一個死迴圈^_^
     */
    public void run() {
        while (true) {
            printMenu();
            processMenuChoice();
        }
    }

    /**
     * 顯示介面在console上面
     */
    private void printMenu() {
        System.out.println("/n/n");
        System.out.println(" Robot Rat Control Menu");
        System.out.println("/n");
        System.out.println(" 1. Pen Up");
        System.out.println(" 2. Pen Down");
        System.out.println(" 3. Turn Right");
        System.out.println(" 4. Turn Left");
        System.out.println(" 5. Move Forward");
        System.out.println(" 6. Print Floor");
        System.out.println(" 7. Exit");
        System.out.println("/n/n/n");
    }

    /**
     * 得到一個作為移動距離的參數
     * 返回整數
     */
    private int getSpaces() {
        int temp = 0;
        try {
            temp = Integer.parseInt(console.readLine());
        } catch (Exception e) {
            System.out.println("Spaces has been set to zero!");
        }
        return temp;
    }

    /**
     * 讀取一個字串然後返回第1個字元
     */
    private char readChar() {
        String s = null;
        System.out.print("Please select from the menu: ");
        try {
            s = console.readLine();
        } catch (Exception ignored) {
        }
        return s.charAt(0);
    }

    /**
     * 介面選擇後調用相應的函數
     */
    private void processMenuChoice() {

        switch (readChar()) {
        case '1':
            setPenUp();
            break;
        case '2':
            setPenDown();
            break;
        case '3':
            turnRight();
            break;
        case '4':
            turnLeft();
            break;
        case '5':
            move();
            break;
        case '6':
            printFloor();
            break;
        case '7':
            exit();
        default:
            printErrorMessage();
        }
    }

    /**
     * Sets the RobotRat's pen to the UP position
     */
    private void setPenUp() {
        pen_position = UP;
        System.out.println("The pen_position is UP");
    }

    /**
     * Sets the RobotRat's pen to the DOWN position
     */
    private void setPenDown() {
        pen_position = DOWN;
        System.out.println("pen_position is DOWN");
    }

    /**
     * Turns the RobotRat to the right
     */
    private void turnRight() {
        switch (direction) {
        case NORTH:
            direction = EAST;
            System.out.println("RobotRat facing EAST");
            break;
        case EAST:
            direction = SOUTH;
            System.out.println("RobotRat facing SOUTH");
            break;
        case SOUTH:
            direction = WEST;
            System.out.println("RobotRat facing WEST");
            break;
        case WEST:
            direction = NORTH;
            System.out.println("RobotRat facing NORTH");
            break;
        default:
            direction = EAST;
            System.out.println("RobotRat facing EAST");
        }
        System.out.println("turnRight() method");
    }

    /**
     * Turns the RobotRat to the left
     */
    private void turnLeft() {
        switch (direction) {
        case NORTH:
            direction = WEST;
            System.out.println("RobotRat facing WEST");
            break;
        case EAST:
            direction = NORTH;
            System.out.println("RobotRat facing NORTH");
            break;
        case SOUTH:
            direction = EAST;
            System.out.println("RobotRat facing EAST");
            break;
        case WEST:
            direction = SOUTH;
            System.out.println("RobotRat facing SOUTH");
            break;
        default:
            direction = EAST;
            System.out.println("RobotRat facing EAST");
        }
    }

    /**
     * This method moves the RobotRat about the floor.
     * @see #getSpaces()
     */
    private void move() {
        System.out.print("Please enter spaces to move: ");
        int spaces = getSpaces();
        switch (pen_position) {
        case UP:
            switch (direction) {
            case NORTH:
                if ((current_row - spaces) <= 0)
                    current_row = 0;
                else
                    current_row = current_row - spaces;
                break;
            case SOUTH:
                if ((current_row + spaces) >= (floor[0].length - 1))
                    current_row = (floor[0].length - 1);
                else
                    current_row = current_row + spaces;
                break;
            case EAST:
                if ((current_col + spaces) >= (floor.length - 1))
                    current_col = (floor.length - 1);
                else
                    current_col = current_col + spaces;
                break;
            case WEST:
                if ((current_col - spaces) <= 0)
                    current_col = 0;
                else
                    current_col = current_col - spaces;
                break;
            }
            break;
        case DOWN:
            switch (direction) {
            case NORTH:
                if ((current_row - spaces) <= 0) {
                    while (current_row >= 1)
                        floor[current_row--][current_col] = true;
                } else
                    while (spaces-- > 0)
                        floor[current_row--][current_col] = true;
                break;
            case SOUTH:
                if ((current_row + spaces) >= (floor[0].length - 1)) {
                    while (current_row < (floor[0].length - 1))
                        floor[current_row++][current_col] = true;
                } else
                    while (spaces-- > 0)
                        floor[current_row++][current_col] = true;
                break;
            case EAST:
                if ((current_col + spaces) >= (floor.length - 1)) {
                    while (current_col < (floor.length - 1))
                        floor[current_row][current_col++] = true;
                } else
                    while (spaces-- > 0)
                        floor[current_row][current_col++] = true;
                break;
            case WEST:
                if ((current_col - spaces) <= 0) {
                    while (current_col >= 1)
                        floor[current_row][current_col--] = true;
                } else
                    while (spaces-- > 0)
                        floor[current_row][current_col--] = true;
                break;
            }
            break;
        }
    }

    /**
     * Prints the floor array pattern to the console
     * @see #floor
     */
    private void printFloor() {
        for (int i = 0; i < floor.length; i++) {
            for (int j = 0; j < floor[i].length; j++) {
                if (floor[i][j] == true)
                    System.out.print('*');
                else
                    System.out.print('0');
            }
            System.out.println();
        }
    }

    /**
     * Exits the RobotRat program
     * @see System#exit
     */
    private void exit() {
        System.exit(0);
    }

    /**
     * Prints error text message when invalid RobotRat menu item entered
     */
    private void printErrorMessage() {
        System.out.println("Please enter a valid menu choice!");
    }

    /**
     * 主函數入口
     */
    public static void main(String[] args) {
        RobotRat rr = new RobotRat(20, 20);
        rr.run();
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.