数组中玩家的位置

为什么我的保安(“S”)与唐纳德(“D”)处于相同的位置。

地图应该像这样打印出来

[D----]

[- - - - -]

[- - - - -]

[- - S - -]

[- - P - -]

但它却像这样显示

[S----]

[- - - - -]

[- - - - -]

[- - - - -]

[- - P - -]


public class Main {


    public static void main(String[] args) {


        Map m = new Map();

        Player p = new Player();

        Donald d = new Donald();

        Security s = new Security();


while(true) {


            m.updateMap(p.row, p.col, p.character);

            m.printMap();

            m.updateMap(p.row, p.col, '-');

            m.updateMap(d.row, d.col, d.character);

            m.updateMap(s.row, s.col, s.character);

            p.move();


        }


    }


}

public class Map {


    char map[][];


    Map() {

        map = new char[5][5];



        for(int i = 0; i<5; i++) {


            for(int j = 0; j<5; j++) {

                map[i][j] = '-';

            }

        }

    }



    void updateMap(int row, int col, char data) {


        map[row][col] = data;

    }



    //prints map on the screen. 

    void printMap() {

        for(int i = 0; i<5; i++) {

            for (int j = 0; j<5; j++) {

                System.out.print(map[i][j] + " ");

            }


            System.out.println();

        }

    }


}

public abstract class Position {


    int row;

    int col;

    char character;

    abstract void move();


}

public class Donald extends Position {


    //Doanld Trump's Position on the Array is [0,0]

    Donald() {

        int row = 0;

        int col = 0;

        character = 'D';

    }


    void move() {


    }


}

正如您在这里看到的,我将安全位置设置为 [3,2],但由于某种原因,它没有将其识别为 [3,2],并将安全位置设置为 Donald 坐的 [0,0]。


public class Security extends Position {


    Security() {

        int row = 3;

        int col = 2;

        character = 'S';

    }


    void move() {


    }


}


湖上湖
浏览 60回答 1
1回答

倚天杖

该类Security继承了属性row和colfrom Position,但在构造函数中,您正在执行以下操作:Security() {&nbsp; &nbsp; int row = 3;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //you are basically creating a new variable called row&nbsp; &nbsp; int col = 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //which is NOT the attribute (that is this.row)&nbsp; &nbsp; character = 'S';}在构造函数之后,Security对象保持s.row等于s.col0。你应该做Security() {&nbsp; &nbsp; this.row = 3;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //you can also do&nbsp; &nbsp; &nbsp; &nbsp; row = 3;&nbsp; &nbsp; this.col = 2;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //and the compiler will understand&nbsp; &nbsp; this.character = 'S';}你在 中犯了同样的错误Donald:你告诉Donald要在位置 (0,0) 但然后你告诉Security要在位置 (0,0),这就是为什么Security出现但Donald没有出现,他被覆盖了Security。Player正如您所设置的,它位于第 4 行第 2 列。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java